3

I am developing a non preemptive multi threading library in linux (in C) . The requirement is to use getcontext setcontext etc to create new threads and manage them. The library is working as expected for 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 extreme conditions, i ran a recursive fibonacci function which creates child threads to calculate sub calculations.I ran fib with increasing numbers and reached the limit at fib 26.

But malloc is not complaining. It is the linux system which reaches OOM and kills the process.

Question: Why is malloc returning success ( a new pointer ) while the system finds itself out of space?

woodstok
  • 2,704
  • 3
  • 34
  • 50

1 Answers1

5

Quoting can i rely on malloc returning null / linux manuals

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer. In case Linux is employed under circumstances where it would be less desirable to suddenly lose some randomly picked processes, and moreover the kernel version is sufficiently recent, one can switch off this overcommitting behavior using a command like: echo 2 > /proc/sys/vm/overcommit_memory

Community
  • 1
  • 1
Marco
  • 7,007
  • 2
  • 19
  • 49