In the case of size zero, malloc(0) can return null (always). That is ambiguous; it looks like a failure. If realloc literally were to call malloc(0) and then treats the null as a failure, it will return the old object. However, on an implementation where malloc(0) always returns null by design, that would be obviously be poor behavior for its own realloc.
If malloc(0) returns null by design that is not a case where allocating an object failed.
We basically now need this in every program that might resize to zero:
void *sane_realloc(void *ptr, size_t size)
{
if (size == 0) {
free(ptr);
return malloc(0);
}
return realloc(ptr, size);
}
The only problem is that if malloc(0) returns null on an implementation where it normally returns an allocated pointer (and thus the call has failed) we don't detect the failure and don't preserve the original object. The application which relies on sane_realloc has to understand that when size is zero, the deallocation always works, whether or not the subsequent malloc does, and so it may get a null pointer on any platform.No comments yet.