The answer is indeed that no modern Unix-like operating system returns on on a successful malloc of zero bytes. This is great. The C standard allowing NULL in this case is quite problematic because it makes code much more complicated.
-
-
Diesen Thread anzeigen
-
First of all code can't check for allocation failure by checking for NULL. Indeed errno need not be set. You need to check for NULL and size is non zero.
Diesen Thread anzeigen -
Second, it's undefined behavior to pass NULL to functions unless they explicitly support it. Even if the function accesses zero bytes. E.g. memcpy(NULL, src, 0) is undefined behavior and the compiler knows this. Now you need to gaurd all these calls with size != 0.
Diesen Thread anzeigen -
Third, a standard property of malloc is that allocations are unique. But allowing malloc(0) == NULL on success means code can't rely on that property.
Diesen Thread anzeigen -
Fourth, code that uses NULL to keep track of unallocated objects can't use a check for non-NULL to check if unallocated. This matters if the allocation is accompanied by some side effect.
Diesen Thread anzeigen -
Of course this only matters for allocations of zero bytes. Most allocations are of fixed size. But things like arrays or byte buffers can easily be empty and naturally be zero bytes. They need to be much more complicated to be portable because of malloc(0) may be NULL.
Diesen Thread anzeigen -
So let's be honest. No remotely relevant operating system does malloc (0) == NULL on success. Most people don't know about it. It causes much more complexity and few things actually handle it. No modern programme language does this.
Diesen Thread anzeigen -
So let's get rid of the standard allowing malloc(0) == NULL on success. The C standard allows it. That could change. If not, POSIX could restrict malloc to not do it. Until then portable software keeps paying the price needlessly.
Diesen Thread anzeigen
Ende der Unterhaltung
Neue Unterhaltung -
-
-
Just tried it on Linux/glibc, Linux/musl, MacOS, FreeBSD, Illumos, Minix, and Cygwin. All except Cygwin returned non-NULL. On Cygwin it crashed with SIGABRT.
-
Also “the platform used by that customer who is using malloc(0) on purpose”. Revisiting all your modelization to allow blocks with validity of length 0 is not fun and many subtle bugs were left to be found in later months, but they were using it to create unique pointers, so…(1)
- Antworten anzeigen
Neue Unterhaltung -
Das Laden scheint etwas zu dauern.
Twitter ist möglicherweise überlastet oder hat einen vorübergehenden Schluckauf. Probiere es erneut oder besuche Twitter Status für weitere Informationen.