Malloc does not fail but the system exits memory
I am developing a non preemptive multithreading library on linux (in C). The requirement is to use getcontext
setcontext
, etc. To create and manage new threads. The library works as expected under normal conditions.
I use malloc for each thread object (MyThread) and I exit gracefully by printing a message "malloc failed"
if malloc returns NULL
. To test for extreme conditions, I ran a recursive fibonacci function that creates child threads to compute subcomputations. I ran fib
with increasing numbers and reached the limit in fib 26
.
But malloc doesn't complain. This linux system reaches OOM
and kills the process.
Question: Why malloc
returns success (new pointer) when the system is out of space?
source to share
Quote can I rely on malloc returning null / Linux tutorials
Linux follows an optimistic memory allocation strategy by default. This means that when malloc () returns non-NULL, there is no guarantee that memory is actually available. This is a very bad mistake. In case the system turns out to be out of memory, one or more processes will be killed by the infamous OOM killer. In the case of using Linux in situations where it would be less desirable to suddenly lose some randomly selected processes and, in addition, the kernel version is quite modern, you can disable this excessive behavior using the command: echo 2> / proc / sys / vm / overcommit_memory
source to share