Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the maximum stack level for a C++ program?

I tried to see how far could I get before getting to a stack overflow by recursion in C++. I wrote this function

long recurse( long level ) {
    std::cout << level << std::endl;
    return recurse( ++level ) * 12 //to avoid tail recursion optimization, if present
}

And I called it passing 0 as the first value. The last number it printed was 349411, then it printed Segmentation fault and stopped running. My guess is it ran out of memory, however the same function called with the same value prints 499982 before throwing a stack overflow error in Lua, and I would be surprised if Lua functions had a so smaller weight on memory than C++ functions.

So what is the maximum stack level a C++ program can get to before stopping its execution?

Is it really "until it has memory", or is there a fixed limit?

Also why does it print Segmentation fault?

Isn't that a message only printed when memory is accessed in unauthorized ways?

like image 690
user6245072 Avatar asked Mar 11 '23 05:03

user6245072


2 Answers

The amount of memory available for recursion depends on the compiler settings, operating system and the physical platform. There is no minimum nor maximum limit.

When you run out of memory, various errors can be printed, one common message is "Segmentation fault."

Also why does it print Segmentation fault?

Isn't that a message only printed when memory is accessed in unauthorized ways?

Your program accessed memory in an unauthorized way by demanding more memory than is available or accessing memory outside your program's scope (allocation), so the operating system was nice and displayed Segmentation fault. You OS could have trashed your computer or hung or rebooted. Some platforms display a Blue Screen Of Death.

like image 187
Thomas Matthews Avatar answered Mar 31 '23 08:03

Thomas Matthews


I would be surprised if Lua functions had a so smaller weight on memory than C++ functions.

You're assuming that Lua is using the C++ stack for doing Lua function calls.

It isn't. Lua has its own stack for its functions, with its own limits. Just like Lua has its own memory space (admittedly provided by the host) and so forth.

The limitations of the C++ stack are implementation dependent and cannot be determined a priori.

Isn't that a message only printed when memory is accessed in unauthorized ways?

Yes. And that's what you did. You attempted to access more stack space than you were allotted. That's accessing memory you have not been authorized to access.

like image 36
Nicol Bolas Avatar answered Mar 31 '23 09:03

Nicol Bolas