|
|
Log in / Subscribe / Register

malloc(0)

malloc(0)

Posted Jan 31, 2022 9:43 UTC (Mon) by NYKevin (subscriber, #129325)
In reply to: malloc(0) by jreiser
Parent article: Handling argc==0 in the kernel

The null pointer satisfies all of the technical requirements of a heap-allocated zero-length array (you can form a pointer that is one past the end, you can iterate over it zero times with a standard for loop, and you can pass it to realloc without breaking anything), and all heap-allocated zero-length arrays are functionally identical because they have no state which can be mutated, so returning NULL can be thought of as semantically equivalent to a copy elision (i.e. you could think of all heap-allocated zero-length arrays as "copies" of the zero-length array that lives at NULL, and then you can elide those copies because zero-length arrays are immutable, so making a copy is unnecessary).

The fact that it happens to vaguely resemble some feature of Lisp, but the standard does not actually require it to fulfill all the requirements of that feature is, frankly, Lisp's problem, not C's problem.


to post comments

malloc(0)

Posted May 28, 2026 11:13 UTC (Thu) by alx.manpages (subscriber, #145117) [Link]

> The null pointer satisfies all of the technical requirements of a heap-allocated zero-length array

This is not correct. You're allowed to do pointer arithmetic on malloc(0) if and only if it returns a non-null pointer. p+0 is valid for any non-NULL p, but NULL+0 has undefined behavior. This limitation of NULL pointers was lifted recently (ISO C2y), but historically it was UB; also, that change might have unexpected consequences, such as lower quality of static analysis, so I suggest not relying too much on it.

P.S.: Sorry for resurrecting this. I was researching the guarantees on argv[0] and read this incorrect statement by chance.


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds