Is there any hard-wired limit on recursion depth in C

前端 未结 4 1517
野的像风
野的像风 2021-02-13 09:54

The program under discussion attempts to compute sum-of-first-n-natural-numbers using recursion. I know this can be done using a simple formula n

相关标签:
4条回答
  • 2021-02-13 10:26

    Generally the limit will be the size of the stack. Each time you call a function, a certain amount of stack is eaten (usually dependent on the function). The eaten amount is the stack frame, and it is recovered when the function returns. The stack size is almost almost fixed when the program starts, either from being specified by the operating system (and often adjustable there), or even being hardcoded in the program.

    • Some implementations may have a technique where they can allocate new stack segments at run time. But in general, they don't.

    • Some functions will consume stack in slightly more unpredictable ways, such as when they allocate a variable-length array there.

    • Some functions may be compiled to use tail-calls in a way that will preserve stack space. Sometimes you can rewrite your function so that all calls (Such as to itself) happen as the last thing it does, and expect your compiler to optimise it.

    It's not that easy to see exactly how much stack space is needed for each call to a function, and it will be subject to the optimisation level of the compiler. A cheap way to do that in your case would be to print &n each time its called; n will likely be on the stack (especially since the progam needs to take its address -- otherwise it could be in a register), and the distance between successive locations of it will indicate the size of the stack frame.

    0 讨论(0)
  • 2021-02-13 10:28

    1)Consumption of the stack is expected to be reduced and written as tail recursion optimization.

    gcc -O3 prog.c

    #include <stdio.h>
    
    unsigned long long int add(unsigned long int n, unsigned long long int sum){
        return (n == 0) ? sum : add(n-1, n+sum); //tail recursion form
    }
    
    int main(){
        printf("result : %llu \n", add(1000000, 0));//OK
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-13 10:29

    The C standard does not define the minimum supported depth for function calls. If it did, which is quite hard to guarantee anyway, it would have it mentioned somewhere in section 5.2.4 Environmental limits.

    0 讨论(0)
  • 2021-02-13 10:36

    There is no theoretical limit to recursion depth in C. The only limits are those of your implementation, generally limited stack space.
    (Note that the C standard doesn't actually require a stack-based implementation. I don't know of any real-world implementations that aren't stack based, but keep that in mind.)

    A SIGSEGV can be caused by any number of things, but exceeding your stack limit is a relatively common one. Dereferencing a bad pointer is another.

    0 讨论(0)
提交回复
热议问题