Comment by worthless-trash

2 months ago

A while back i remember looking at the kernel source code, when overcommit is enabled, malloc would not fail if it couldnt allocate memory, it would ONLY fail if you attempted to allocate memory larger than the available memory space.

I not think you can deal with the failure condition the way you think on Linux (and I imagine other operating systems too).

It's very easy to make malloc return NULL:

  % ulimit -v 80000
  
  % cat test.c
  #include <stdio.h>
  #include <stdlib.h>
  
  int main(void) {
    char *p = malloc(100'000'000);
    printf("%p\n", p);
  }
  
  % cc test.c
  
  % ./a.out
  (nil)

The bug was about the case when malloc returns null, but the library doesn't check for it.

  • Correct, but the point is that it is difficult to get malloc to return null on Linux. Why litter your code with checks for de facto impossible scenarios?

    • in systems level programming (the introductory course before operating systems in our university) this was one of the first misconceptions to be eradicated. you cannot trust malloc to return null.

    • First, Linux has thousands of settings that could affect this, second the library probably works not only on Linux.