Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I exhaust stack?

Tags:

c++

stack

I know that by using operator new() I can exhaust memory and I know how to protect myself against such a case, but can I exhaust memory by creating objects on stack? And if yes, how can I check if object creation was succesful?
Thank you.

like image 908
There is nothing we can do Avatar asked Dec 09 '22 14:12

There is nothing we can do


2 Answers

You can exhaust a stack. In such cases, your program will probably crash with the stack overflow exception immediately.

A stack has a size too, so you can look at it as simply a block of memory. Variables inside functions for example are allocated here. Also when you call a function, the call itself is stored on the stack (very simplified, i know). So if you make a infinite recursion (as mentioned in another answer) then the stack gets filled but not emptied (this happens when a function returns, the information about the call is "deleted") so at some time you will fill the whole space allocated for your programs stack and your app will crash.

Note that there are ways how to determine/change the size of stack.

like image 77
PeterK Avatar answered Dec 12 '22 05:12

PeterK


Just look at the title of this site and you will see the answer. Write some infinite recursion if you want to see "live" what happens.

i.e.

void fun() { fun(); }
like image 24
Klark Avatar answered Dec 12 '22 04:12

Klark