[PATCH v2 3/4] Say malloc (0) != NULL is now common; resection
DJ Delorie
dj@redhat.com
Thu Feb 12 18:28:00 GMT 2026
Paul Eggert <eggert@cs.ucla.edu> writes:
>> We should add a note about how to be portable (that's the purpose of
>> this section, yes? ;) like "Thus, portable programs should never pass a
>> size of zero to allocation functions."
>
> I wouldn't go that far, as it's portable to pass 0 to malloc, so long as
> you're willing to deal with the resulting null pointer.
Posix says "If the size of the space requested is 0, the behavior is
implementation-defined". An application that can accept more than one
implementation's definition has been ported, but is not portable. Yes,
posix defines two possible behaviors, but still leaves the non-null
returned pointer's access undefined.
To fully avoid undefined or implementation-defined behavior, a portable
program should avoid this completely by never passing zero to malloc.
More information about the Libc-alpha
mailing list