3 ms·
IIRC, C says that you get a real pointer back from malloc(0). Repeated calls return distinct pointers. For whatever that's worth...
by AnimalMuppet 12y ago
IIRC, C says that you get a real pointer back from malloc(0). Repeated calls return distinct pointers.
For whatever that's worth...
- duaneb 12y agoAs someone who is pretty good at allocators, if you're calling `malloc(0)` you're wandering into very undefined territory. I've seen everything from valid allocations of non-zero length, whatever was on the stack, and just 0. The only real constraint is that free accepts the returned pointer.
- readerrrr 12y agoActually it is implementation defined. You may get a NULL pointer or a non-NULL pointer which may not be dereferenced. This is intentional so that you can always call free on a pointer received from malloc functions, regardless of the allocation result.( passing a NULL to free is ok )
- pbsd 12y agoNot exactly; from §7.20.3 in C99: 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.
- AnimalMuppet 12y agoAh, my error. But, quoting from my ancient copy of The C++ Programming Language, volume 2, §r5.3.3: "This implies that an operator new() can be called with the argument zero. In this case, a pointer to an object is returned. Repeated such calls return pointers to distinct objects." So my memory was from C++ new, not C malloc.
- mcguire 12y ago"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" I love the C standards. Is that defining the behavior of malloc or the behavior of the code calling malloc?
- pbsd 12y agoThe caller code. It is saying that the caller cannot dereference the returned pointer, under pain of undefined behavior.
- AnimalMuppet 12y agoIn particular, you can't access (read or write) off either end of an allocated block. Well, if the block is of (nominal) length 0, there is nowhere to access safely.