Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding stack reuse of a function calling itself?

if a function calls itself while defining variables at the same time would it result in stack overflow? Is there any option in gcc to reuse the same stack.

void funcnew(void)
{
   int a=10;
   int b=20;
   funcnew();
   return ;
 }

can a function reuse the stack-frame which it used earlier? What is the option in gcc to reuse the same frame in tail recursion??

like image 424
lazy_hack Avatar asked Feb 12 '10 09:02

lazy_hack


2 Answers

Yes. See

-foptimize-sibling-calls

Optimize sibling and tail recursive calls.

Enabled at levels -O2, -O3, -Os.

Your function is compiled to:

funcstack:
.LFB0:
    .cfi_startproc
    xorl    %eax, %eax
    jmp func
    .cfi_endproc

(note the jump to func)

Reusing the stack frame when a function end by a call -- this include in its full generality manipulating the stack to put the parameters at the correct place and replacing the function call by a jump to the start of the function -- is a well known optimisation called [i]tail call removal[/i]. It is mandated by some languages (scheme for instance) for recursive calls (a recursive call is the natural way to express a loop in these languages). As given above, gcc has the optimisation implemented for C, but I'm not sure which other compiler has it, I would not depend on it for portable code. And note that I don't know which restriction there are on it -- I'm not sure for instance that gcc will manipulate the stack if the parameters types are different.

like image 163
AProgrammer Avatar answered Sep 18 '22 01:09

AProgrammer


Even without defining the parameters you'd get a stackoverflow. Since the return address also is pushed onto the stack.

It is (I've learned this recently) possible that the compiler optimizes your loop into a tail recursion (which makes the stack not grow at all). Link to tail recursion question on SO

like image 39
Toad Avatar answered Sep 18 '22 01:09

Toad