If realloc fails and returns NULL is the former buffer free'd or it is kept intact? I didn't found that particular piece of information in the man page and I'm quite unsure what to do. If memory is freed then double-free could be risky. If not then the leakage would occur.
realloc() returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and may be different from ptr, or NULL if the request fails. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails the original block is left untouched; it is not freed or moved.
No, it does not. That aspect has often annoyed me since you can't just use:
if ((buff = realloc (buff, newsize)) == NULL)
return;
in your code. Instead you have to do something like:
if ((newbuff = realloc (buff, newsize)) == NULL) {
free (buff);
return;
}
buff = newbuff;
Of course, I understand the rationale behind keeping the original buffer intact on failure but my use case has popped up enough that I generally code a realloc2()
to handle that case, something like (from memory):
static void *realloc2 (void *old, size_t sz) {
void *new = realloc (old, sz);
if ((new == NULL) && (old != NULL)) free (old);
return new;
}
Aside: yes, I know that you can free(NULL)
but old (defensive programming) habits die hard (and it avoids an unnecessary function call).
The relevant section in the draft (n1362) of C1x states:
7.20.3.4 The realloc function
If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.
no any changes of the former buffer if realloc() failed.
man realloc(3):
realloc() returns a pointer to the newly allocated memory, which is suitably
aligned for any kind of variable and may be different from ptr, or NULL if the
request fails. If size was equal to 0, either NULL or a pointer suitable to be
passed to free() is returned. If realloc() fails the original block is left
untouched; it is not freed or moved.