Re: when can realloc fail?



On Apr 1, 9:06 pm, Eric Sosman <esos...@xxxxxxxxxxxxxxxxxxx> wrote:
banan...@xxxxxxxxxxxx wrote:
Hi,
I just want to get this right.
A call to realloc() will return NULL on error and the original memory
is left untouched,
both when requesting a larger or a smaller size that the original,
right?
But a call to realloc() with size set to zero is equivalent to free(),
with returns void.
Does that mean that a call to realloc() can fail when shinking memory
except when
shrinking it to zero in which case it will always succeed?

Yes, realloc() can fail when shrinking an allocation, or
when growing it, or even when leaving its size unchanged.

When reallocating to zero size, the situation is complicated.
C90 says "If size is zero and ptr is not a null pointer, the
object it points to is freed." Since free() cannot fail (given
an argument that doesn't invoke undefined behavior), it follows
that realloc(...,0) cannot fail.

But C99 has no such text, and makes no special case for size
zero. All we're told is that realloc(...,0) either fails or it
returns a pointer to an object of size zero. Nothing I can find
in C99 forbids realloc(...,0) to fail, so presumably it can.

Thank you for your reply!
But I wonder, if realloc(...,0) fails in C99, how can I know that?
How can I know if a returned NULL means that realloc() failed,
or if it is the pointer to the new memory, empty, which is NULL.
(That is what I got on my compiler anyway)

.



Relevant Pages

  • Re: when can realloc fail?
    ... A call to reallocwill return NULL on error and the original memory ... But a call to realloc() with size set to zero is equivalent to free, ...
    (comp.lang.c)
  • Re: Can I Trust Pointer Arithmetic In Re-Allocated Memory?
    ... mostenly when you tries to blame the compiler you blames yourself ... p is the pointer holding the address of the memory block. ... result of realloc until you knows that realloc returns memory ... You should initialise any variable when defining it to be sure to fail ...
    (comp.lang.c)
  • Re: when can realloc fail?
    ... A call to reallocwill return NULL on error and the original memory ... But a call to realloc() with size set to zero is equivalent to free, ... Does that mean that a call to realloccan fail when shinking memory ...
    (comp.lang.c)
  • Re: realloc question
    ... By returning NULL, realloc lets you know ... >> that your memory block still has its original size. ... > Not that having a memory block reduction fail is something difficult to ...
    (comp.lang.c)
  • Unit testing malloc and free
    ... Does anyone have a completely portable way to cause malloc and free to ... fail. ... I've tried to simply realloc until I run out of memory in N byte ...
    (comp.software.testing)