3 ms·
It's worth noting that realloc(ptr, 0) behavior is undefined. The vast majority of modern C libraries will implement it as return free(ptr), NULL;
by apankrat 8y ago
It's worth noting that
realloc(ptr, 0)
behavior is undefined. The vast majority of modern C libraries will implement it as
return free(ptr), NULL;
and it will be documented on man pages as such, but there are systems where this will be equivalent to
return free(ptr), malloc(0);
Furthermore, in theory, this is also permitted:
return NULL;
so as tempting as realloc() might be as a single override for implementing custom allocators, there are some worms.
- tom_ 8y agoRealloc's behaviour is well-defined: https://port70.net/~nsz/c/c11/n1570.html#7.22.3.5p3 https://port70.net/~nsz/c/c11/n1570.html#7.22.3.5p3 If the size of the space requested is zero, the behavior is implementation-defined: https://port70.net/~nsz/c/c11/n1570.html#7.22.3 https://port70.net/~nsz/c/c11/n1570.html#7.22.3
- deleted 8y ago[deleted]
- richardwhiuk 8y agoBeing implementation defined is hardly well defined.
- tom_ 8y agoNo... maybe? It's probably arguable, even if it's not an interesting argument. Either way, realloc's behaviour is well-defined when the pointer is null.
- apankrat 8y agoWell, it's the return value in realloc(ptr, 0) case that is implementation-specific, but its behavior _is_ well-defined - it is expected to "deallocate the old object". My point was that in reality the behavior varies. "Undefined" in a common tongue sense, not in the terms of the C standard.