Jon Sargeant
2007-Oct-06 16:14 UTC
[LLVMdev] 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
Dale Johannesen
2007-Oct-06 16:35 UTC
[LLVMdev] malloc(), free(), and alloca() with zero size
On Oct 6, 2007, at 9:14 AM, Jon Sargeant 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.
Jon Sargeant
2007-Oct-07 16:19 UTC
[LLVMdev] malloc(), free(), and alloca() with zero size
Dale Johannesen wrote:> On Oct 6, 2007, at 9:14 AM, Jon Sargeant 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