BUG: realloc(p,0) should be consistent with malloc(0)
H. Peter Anvin
hpa@zytor.com
Fri Jun 20 23:58:04 GMT 2025
On 2025-06-17 04:52, Wilco Dijkstra wrote:
> Hi Alejandro,
>
>>> The purpose of realloc(p, 0) is to free memory.
>>
>> No. The purpose of realloc(p,0) is to resize a block to size 0.
>
> That's arguing semantics. Whether you return the original block or a new
> small block is an internal implementation detail. The goal is to free the memory.
>
There is actually a third option.
If a non-NULL pointer is returned, from either malloc or realloc, it
needs to be unique, but there is no requirement that it needs to be
*accessible.*
In other words, glibc could reserve a chunk of address space using
mmap(..., PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE, ...) and
simply allocate pointers out of that space. Accessing those pointers
will SIGSEGV (or SIGBUS, on alignment error), as they should as that is
not valid storage even for a single byte; system calls will return EFAULT.
This is BETTER than making a small allocation, since it will trap on any
reference to the dummy pointer.
It *could* keep a bitmask of allocations, or it could simply keep a high
water marker and ignore free() [and realloc() to a nonzero-sized object]
entirely. Especially on 64-bit architectures that is definitely an
option, since there is enough pointer space available that any realistic
failure would be many centuries in the future.
On many architectures (especially 64-bit architectures) it could also
just point into invalid address space and not even bother with
reservations; like non-canonical address space on x86-64, providing an
for all practical purposes inexhaustible supply of invalid pointer
addresses.
-hpa
More information about the Libc-alpha
mailing list