3 ms·
> So what happens if realloc(p, 0) fails? It's going to return NULL, since that's what realloc does if it fails; but should it also free the allocation p? The
by carussell 11y ago
> So what happens if realloc(p, 0) fails? It's going to return NULL, since that's what realloc does if it fails; but should it also free the allocation p? The sane answer is yes
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".
- cperciva 11y agoFreeing 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".
- carussell 11y agoI'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?
- cperciva 11y agoSome 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.
- pcwalton 11y ago> 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]). [1]: http://www.openwall.com/lists/musl/2013/01/15/1 http://www.openwall.com/lists/musl/2013/01/15/1
- cperciva 11y agoUnfortunately, as I wrote in the commit message which spawned this thread, this just encourages people to write more buggy programs.
- pcwalton 11y agoOr, 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.
- fanf2 11y agoA standards-conforming realloc will never try to allocate 0 bytes: it is required to free in that case.
- cperciva 11y agoAlas, C11 seems to have bungled this.
- masklinn 11y agoThe 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)
- fanf2 11y agoYes. I had not previously noticed this. What a disaster.