I'm developing application for an embedded system with limited memory (Tegra 2) in C++. I'm handling NULL results of new
and new[]
throughout the code which sometimes occurs but application is able to handle this.
The problem is that the system kills the process by SIGKILL if the memory runs out completely. Can I somehow tell that new
should just return NULL instead of killing the process?
I am not sure what kind of OS You are using, but You should check if it supports opportunistic memory allocation like Linux does.
If it is enabled, the following may happen (details/solution are specific to the Linux kernel):
new
or malloc
gets a valid address from the kernel. Even if there is not enough memory, because ...Solution: Disable overcommitting of memory:
echo 2 > /proc/sys/vm/overcommit_memory
Two ideas come to mind.
Write your own memory allocation function rather than depending on new
directly. You mentioned you're on an embedded system, where special allocators are quite common in applications. Are you running your application directly on the hardware or are you running in a process under an executive/OS layer? If the latter, is there a system API provided for allocating memory?
Check out C++ set_new_handler
and see if it can help you. You can request that a special function is invoked when a new
allocation fails. Perhaps in that function you can take action to prevent whatever is killing the process from executing. Reference: http://www.cplusplus.com/reference/std/new/set_new_handler/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With