Re:Once upon a time, memory allocators made sense
by cperciva on Monday January 18, 2016 @02:40PM
(#10926398)
Freeing a memory allocation is guaranteed to never fail. Allocating zero bytes can fail (with dumb C libraries). The question is "if realloc fails to allocate zero bytes, should it still free the original allocation".
Re:Once upon a time, memory allocators made sense
by pcwalton on Monday January 18, 2016 @03:10PM
(#10926578)
> Allocating zero bytes can fail (with dumb C libraries).
They might not be dumb; they might be forced into it to maintain compatibility with buggy programs and/or configure scripts (e.g. [1]).
Re:Once upon a time, memory allocators made sense
by cperciva on Monday January 18, 2016 @03:13PM
(#10926597)
Unfortunately, as I wrote in the commit message which spawned this thread, this just encourages people to write more buggy programs.
Re:Once upon a time, memory allocators made sense
by pcwalton on Monday January 18, 2016 @03:21PM
(#10926641)
Or, more likely, it just encourages customers to abandon your alternative C library in favor of glibc to avoid breaking configure scripts (which is what forced musl's hand). I definitely think you're right in principle, but I can't blame musl's author for bowing to market pressure any more than I can blame Intel for sticking to x86 backwards compatibility.
Re:Once upon a time, memory allocators made sense
by carussell on Monday January 18, 2016 @02:59PM
(#10926512)
I'm still not clear on this. What does "allocating zero bytes" mean, if not "free the original allocation"? Keep the malloc metadata structures around but update their size to 0?
Re:Once upon a time, memory allocators made sense
by cperciva on Monday January 18, 2016 @03:09PM
(#10926573)
Some systems handle a zero-byte allocation request by allocating a unique non-NULL pointer which cannot be dereferenced. If they run out of unique pointers, they can fail to allocate zero bytes.
Re:Once upon a time, memory allocators made sense
by fanf2 on Monday January 18, 2016 @07:25PM
(#10928061)
A standards-conforming realloc will never try to allocate 0 bytes: it is required to free in that case.
Re:Once upon a time, memory allocators made sense
by cperciva on Monday January 18, 2016 @07:50PM
(#10928149)
Alas, C11 seems to have bungled this.
Re:Once upon a time, memory allocators made sense
by masklinn on Tuesday January 19, 2016 @06:01AM
(#10929906)
The change appeared in C99 apparently, in my ISO/IEC 9899:1999 PDF the part about a 0-sized realloc being equivalent to a free has already been removed, and that a 0-sized allocation can return either a NULL or a non-null pointer has appeared under implementation-defined behaviours (j.3.12)
If realloc(p, 0) is a synonym for free(p), what does it mean for it to "also free the allocation p" in the event of failure? Unpacking it, the statement seems to be saying the same thing as, "if it fails, then what it should do is to not fail".