What would happen if after using malloc it returned a NULL pointer and you went ahead and try to use that pointer?

Viewed 92

I know that after using malloc, you have to make sure that the returned pointer is not NULL, but what if you didn't?

1 Answers

Regarding using a null pointer with the * operator, the 2011 C standard (committee draft N1570) says in clause 6.5.3.2, paragraph 4: “If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.” A footnote notes that a null pointer is an invalid value.

Many people will think of using a null pointer as trying to access memory with an invalid address, which causes an exception and terminates your program on common hardware and operating systems. However, modern compilers and their optimizers are very complicated and perform a variety of abstract mathematical transformations on your code. The result is that, if your code has undefined behavior, a variety of surprising things can happen.

Using a null pointer in other ways can also cause undefined behavior, including using it with the -> operator, the subscript operator, the + and - binary operators, and the relational operators (<, <=, >, and >=).

Related