Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if my app is out of memory?

If my application is out of memory when i call new() i will get exception and malloc() i will get 0 pointer.

But what if i call a method with some local variables? They occupy memory too. Is there some way to reserve memory for "normal" variables? So that even though new() throws exception i can just catch it, fix stuff and still call methods like usual.

like image 389
Michael Avatar asked Jan 21 '26 13:01

Michael


2 Answers

Your data is allocated in one of three ways:

  • Statically allocated data (static members or globals) are allocated when the app starts up, which means that they're not really going to be a problem.
  • Stack allocated data is allocated on the stack (surprise!) The stack is an area of memory that's set aside for local variables and function stackframes. If you run out of space there, it's undefined what happens. Some implementations might detect it and give you an access violation/segmentation fault, and others will just make you overwrite heap data. In any case, there's no way to detect this, because in general, there's no way to handle it. If you run out of stack space, there's just nothing you can do. You can't even call a function, because that takes up stack space.
  • Heap allocated memory is what you use when you call new/malloc. Here, you have a mechanism to detect out-of-memory situations, because you may be able to handle it. (Instead of allocating 200mb, you might be able to make do with 100mb, and just swap the data out halfway through)

You generally shouldn't run out of stack space unless you perform some heavy recursion though.

like image 147
jalf Avatar answered Jan 24 '26 03:01

jalf


THe C++ language doesn't provide any mechanism for reserving memory for local variables. Your specific C++ implementation and/or operating system may provide some means of increasing the total stack size, but this is not normally necessary.

Note also that if a call to new does fail, there is probably very little you can practically do to recover from it. Many people (me included) no longer bother checking for new failure.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!