Can the compiler assume that malloc will never return NULL?

In this video it is mentioned that the compiler can assume that malloc never returns NULL and is allowed to optimize accordingly. I have never heard of this and couldn’t find any reference to it in the C-Standard. Can anyone tell me if this is true and if so, where this behaviour is specified?

The code shown in the video at this point is:

if((a = malloc(1024)) == NULL)
    printf("We are out of memory!\n");
else
    free(a);

>Solution :

The speaker does not mean the compiler can assume malloc never returns a null pointer. They mean in the specific case shown, the compiler can see what the code does and that it can be implemented without calling malloc at all and, equivalently, it can be optimized as if malloc never returns null in that specific situation.

The C standard allows a compiler to implement code in any way that produces the specified observable behavior, which is, from C 2018 5.1.2.3 6:

  • Accesses to volatile objects are evaluated strictly according to the rules of the abstract machine.
  • At program termination, all data written into files shall be identical to the result that execution of the program according to the abstract semantics would have produced.
  • The input and output dynamics of interactive devices shall take place as specified in 7.21.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input.

Note that malloc is not part of the observable behavior. It is inside the C implementation, which means the compiler is allowed to optimize how it behaves. Even if there is a separate library that provides malloc, the compiler is allowed to treat that as just an assist to C implementation and optimize uses of malloc in the program.

Leave a Reply