Malloc null checks, why sometimes are moved and sometimes not?


Here is simple test code:

LLVM generally assumes that malloc never fails.

But I dont understand difference between these two example functions - and why null check was not removed in f1, since in f2 it was removed.


That's because the return value from malloc is discarded in f2. In that case it simply doesn't matter if the malloc happened or not, and can be assumed to have succeeded.

In the first case, the pointer is returned from the function, which means that someone may actually want to access the allocated storage.


Wouldn't such assumption be too aggressive?

Normally, yes, but the standard explicitly allows the compiler to not call allocation/deallocation functions if the storage can be provided in another way. If the storage that would have been allocated by malloc cannot ever be accessed, we can pretend that it has been successfully provided in some way.