Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forsee std::bad_alloc in C++

Tags:

c++

As far as I understand std::bad_alloc exceptions in C++ are triggered when the program runs out of memory. Is there a way to monitor how much memory left there are and trigger a special routine before we reach the point of no return ?

like image 751
0x26res Avatar asked Jan 19 '26 20:01

0x26res


1 Answers

No, but you can register a handler with std::set_new_handler, which the default implementation of the global operator new() executes in a loop until either the handler doesn't return or there is no further handler registered. The handler may itself try to free up some more memory, or post a log message, or something similar.

The specifics of how much memory are available for your allocation function depend very heavily on your platform and your operating system, though, so don't expect too much.

For example, on systems that oversubscribe memory, your allocations may succeed, but your program could still die because the system is out of memory.

like image 65
Kerrek SB Avatar answered Jan 22 '26 10:01

Kerrek SB



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!