开发者

if im calling recursive function without any parameter then stackoverflow error occur so what is the reason behind this [duplicate]

开发者 https://www.devze.com 2023-01-02 05:52 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Recursive main() - why does it segfault?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Recursive main() - why does it segfault?

if im calling recursive function without any parameter then stackoverflow error o开发者_JS百科ccur so what is the reason behind this


This is implementation-specific, but is used on numerous platforms. When a function needs to return the processor needs to know where exactly it was called from - so-called return address.

That return address needs to be stored prior to calling the function. In many implementations the program stack is used for storing the return addresses as well as for storing the parameters. So even when there're no parameters to the function program stack is still used and too deep of recursion causes stack overflow.


No parameter? Then where is your terminating condition?

void infinity()
{
    infinity();
}


A recursive function with no parameters doesn't make a lot of sense, as you would have no controlling variable with which to terminate the recursion.


The value of program counter (PC) or Instruction pointer (PC is a register stores address to next instruction) is pushed into stack just before executing a function and value of PC is changed to first instruction of the function, after finishing the old value (poped out) retained by PC. In infinite recursion the value is pushed again and again. Hence the stack overflow.

0

精彩评论

暂无评论...
验证码 换一张
取 消