BUG: realloc(p,0) should be consistent with malloc(0)

Paul Eggert eggert@cs.ucla.edu
Thu Jun 19 19:17:19 GMT 2025


On 2025-06-18 16:32, Alejandro Colomar wrote:
> For this, I need a two-step change:
> 
> 1)  Define realloc(p,n) to be equivalent to free(p) and malloc(n), plus
>      moving the contents, plus not freeing on error.
> 
> 2)  Require that malloc(0) returns non-null.
> 
> The only implementations that need to be fixed to comply with step 1 are
> glibc, Bionic, and Windows, as far as I know.
> 
> There are existing implementations that need to be fixed to comply with
> step 2, and I don't know how many.

The only such implementation I know of is AIX, which has the following 
properties:

1. malloc(0) and realloc(NULL,0) return NULL without setting errno. This 
conforms to POSIX.1-2017 (which is all that AIX attempts to conform to) 
but not to POSIX.1-2024.

2. When p is not null, realloc(p,0) frees p, returns NULL, and sets 
errno=EINVAL. This conforms to both POSIX.1-2017 and POSIX.1-2024.

3. However, if you compile with GCC (I tested GCC 10.3 on AIX 7.3) and 
use -D_LINUX_SOURCE_COMPAT, AIX behaves like glibc 2.1 and earlier, 
namely, malloc(0) returns a nonnull pointer on success, and realloc(p,0) 
is consistent with malloc(0). This conforms to both POSIX.1-2017 and 
POSIX.1-2024.

4. However however, if you compile with IBM's compiler (I tested 
ibm-clang 17.1.1 on AIX 7.3) and use -D_LINUX_SOURCE_COMPAT, malloc(0) 
returns NULL without setting errno, and realloc(p,0) behaves like glibc 
2.1 and earlier. As far as I know this behavior is unique among 
operating systems: it disagrees with all versions of glibc and it does 
not conform to either POSIX.1-2017 or POSIX.1-2024 (though of course AIX 
does not promise conformance when _LINUX_SOURCE_COMPAT is defined).

5. There is no way in AIX to get glibc's current behavior, where 
malloc(0) and realloc(NULL,0) return non-null on success and 
realloc(p,0) succeeds and returns NULL.

I suspect that (4) is simply a bug, that IBM intended IBM's compiler to 
behave like GCC, and that IBM hasn't bothered to fix the bug because 
nobody has reported it, as application developers long ago gave up on 
trying to use malloc(0) and realloc(p,0) on AIX.



More information about the Libc-alpha mailing list