malloc(), free(), and alloca() with zero size

If <NumElements> is zero, what is the behavior of malloc() and alloca()?
Can I call free() using the pointer that malloc() returns?

Also, I'm assuming that free()ing a null pointer is a legal NOP?

Regards,
Jon

If <NumElements> is zero, what is the behavior of malloc() and alloca()?
Can I call free() using the pointer that malloc() returns?

alloca is not standard.
The behavior of malloc is covered in 7.20.3p1:

If the size of the space requested is zero, the behavior is implementation-defined:
either a null pointer is returned, or the behavior is as if the size were some
nonzero value, except that the returned pointer shall not be used to access an object.

Portable code can't depend on either behavior, obviously. It is usually simplest to avoid using malloc(0).

Also, I'm assuming that free()ing a null pointer is a legal NOP?

Yes, 7.20.3.2p2.

Dale Johannesen wrote:

If <NumElements> is zero, what is the behavior of malloc() and alloca()?
Can I call free() using the pointer that malloc() returns?

alloca is not standard.
The behavior of malloc is covered in 7.20.3p1:

If the size of the space requested is zero, the behavior is implementation-defined:
either a null pointer is returned, or the behavior is as if the size were some
nonzero value, except that the returned pointer shall not be used to access an object.

Portable code can't depend on either behavior, obviously. It is usually simplest to avoid using malloc(0).

Also, I'm assuming that free()ing a null pointer is a legal NOP?

Yes, 7.20.3.2p2.

Ok, just to be clear...
The semantics of the LLVM malloc and free instructions and the llvm.memcpy, llvm.memmove, and llvm.memset intrinsics are the same as their C counterparts (except for the extra alignment parameter). The LLVM alloca instruction is not standard, so does that mean alloca()ing zero elements is undefined?

Regards,
Jon

In the LLVM IR, alloca of zero elements is legal, but not defined. You can't dereference the returned pointer.

-Chris