Sigkill While Allocating Memory in C++

SIGKILL while allocating memory in C++

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):

  1. Your new or malloc gets a valid address from the kernel. Even if there is not enough memory, because ...
  2. The kernel does not really allocate the memory until the very moment of the first access.
  3. If all of the "overcommitted" memory is used, the operating system has no chance but killing one of the involved processes. (It is too late to tell the program that there is not enough memory.) In Linux, this is called Out Of Memory Kill (OOM Kill). Such kills get logged in the kernel message buffer.

Solution: Disable overcommitting of memory:

echo 2 > /proc/sys/vm/overcommit_memory

Why does malloc() or new never return NULL?

Linux, by default, usually uses an opportunistic memory allocation scheme, meaning the kernel will give you a valid address that won't be allocated until first use.

See:

  • SIGKILL while allocating memory
  • C Program on Linux to exhaust memory

According to those responses you can turn this feature off using echo 2 > /proc/sys/vm/overcommit_memory.

From what I can tell, this is done under the assumption that you wont necessarily use all the memory that you allocate. I can't say that I personally ever allocate space that I don't touch at least once, so I'd be curious to know how this affects real life performance...

Regarding the SIGKILL failure, every malloc you call is still allocating some memory for each call. Eventually you will likely fill your memory with malloc overhead and thus evoke the fury of the out of memory kill feature. Whether this alone is the issue or if perhaps the overcommit policy still allocates some fraction of the requested space is a good question.

How to free dynamic allocated variable by SIGTERM?

I doubt that you need to. Any OS which supports fork(), will also automatically free allocations from malloc() when a process exits, regardless of how it does so (including termination).

There do exist environments where C programs don't run in processes, and where you have to be very careful what you leave lying around at exit. But those environments aren't POSIX, and won't support fork(). They might not support signals, for that matter. If you're writing for any such unusual environment, check your documentation...

If you want to see a clean valgrind report, then you could have the handler stick an event into the child's event loop (or set a flag and post a semaphore, or whatever), and process the event as a clean exit. That's also what you'd do if your program was an interactive application and you wanted to save the user's data on a SIGTERM, assuming your UI framework didn't already translate SIGTERM into an event for you.



Related Topics



Leave a reply



Submit