0

This question is a follow-up to Why does malloc() or new never return NULL? and SIGKILL while allocating memory in C++:

From the answers there I can understand why a program would be killed when trying to write to memory which was "successfully" allocated by malloc. However, I see the same problem when using calloc (on SLC and Ubuntu):

Instead of returning a null pointer, the program is SIGKILLed, so checking the return value of calloc is futile. But calloc should not be affected by the "overcommit feature"? (Unless it is relying on malloc behind the scenes...)

Community
  • 1
  • 1
fuenfundachtzig
  • 7,952
  • 13
  • 62
  • 87
  • Hm, actually it seems to do: https://code.google.com/p/source-code-reading/source/browse/trunk/malloc/calloc.c – fuenfundachtzig Jun 25 '14 at 09:10
  • Why would you assume that `calloc` wouldn’t rely on `malloc`? Of course it doesn’t *have* to – but the natural implementation is obviously as a thin wrapper around `malloc`. – Konrad Rudolph Jun 25 '14 at 09:22
  • I did not assume that. It doesn't have to, and even knowing that it does, it would have been possible that it did not allow `malloc` to return memory which is not backed up by "real" memory. (Which depends on where the setting in `/proc/sys/vm/overcommit_memory` comes into the game.) – fuenfundachtzig Jun 25 '14 at 09:36

1 Answers1

1

From proc /proc/sys/vm/overcommit_memory section

The amount of memory presently allocated on the system. The committed memory is a sum of all of the memory which has been allocated by processes, even if it has not been "used" by them as of yet. A process which allocates 1GB of memory (using malloc(3) or similar), but only touches 300MB of that memory will only show up as using 300MB of memory even if it has the address space allocated for the entire 1GB. This 1GB is memory which has been "committed" to by the VM and can be used at any time by the allocating application. With strict overcommit enabled on the system (mode 2 /proc/sys/vm/overcommit_memory), allocations which would exceed the CommitLimit (detailed above) will not be permitted. This is useful if one needs to guarantee that processes will not fail due to lack of memory once that memory has been successfully allocated.

Although only malloc is explicitly listed, it does say similar, calloc (and realloc) are the similar. It has the same issue as malloc on this matter.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294