Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Which platforms return a non-null pointer on malloc(0)
What is the portability of malloc(0);
?
- Which platforms return
NULL
without settingerrno
? - Which platforms return a non-null pointer?
- Do any platforms have some other behavior?
2 answers
It is trivial enough to test:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define KNOWN_GARBAGE ((int*)~0u)
int main (void)
{
int* ptr = KNOWN_GARBAGE;
ptr = malloc(0);
int errno_changed = errno;
if(ptr == NULL)
puts("Returned NULL.");
else if(ptr == KNOWN_GARBAGE)
puts("Didn't modify the pointer, non-conforming?");
else
puts("Returned non-zero, modified the pointer.");
if(errno_changed)
printf("Weird use of errno detected, error code 0x%X\n", errno_changed);
}
Then try it with whatever compiler, version, standard lib and system you want. The vast majority of gcc-like compilers + libc flavours appear to return a new non-zero address.
The setting errno
part appears to be some old Unix gunk from the 90s according to man
(?), so you may have to find some sufficiently obscure computer for that, I guess.
Related to this question: C no longer has standard support for realloc(ptr, 0)
since C23 likely comes with major defects here. See realloc(ptr, 0) in C23 - now what?
The behavior of malloc(0)
is implementation-defined and varies between platforms. Some platforms will return a NULL pointer, others might return a non-null pointer, but such a pointer should not be used. There's no widely known behavior outside of these.
1 comment thread