Re: when can realloc fail?



<banansol@xxxxxxxxxxxx> wrote in message
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?

It is a bit of a grey area.

Normally you want the construct

temp = realloc(ptr, newsize);
if(temp == 0)
{
fprintf(stderr, "Oh no, out of memory\n");
free(ptr);
return -1;
}
ptr = temp;
..... /* do something useful */
free(ptr);
return 0;

it is quite a lot of code simply to perform memory management. However if newsize is zero you've entered a grey area. temp could be zero or a valid pointer assuming that the function doesn't fail. If we say that realloc() must return a pointer to a block of no memory then you've also got the potential for a fail. Then it is not unlikely that your code, knowing that newsize is zero and it is working on an empty data set, will forget to call free() on ptr.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm


.



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, ... Does that mean that a call to realloccan fail when shinking memory ...
    (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)
  • when can realloc fail?
    ... A call to reallocwill return NULL on error and the original memory ... both when requesting a larger or a smaller size that the original, ... But a call to realloc() with size set to zero is equivalent to free, ...
    (comp.lang.c)
  • Re: How to get the memory block size which allocated by new operator?
    ... memory that not released.When allocate memory by new operator,I will ... set of memory management routines that are far superiour to malloc, realloc, ... Programmers know when they're combining multiple outputs into a single ... NULL is stuffed into pbBuf when realloc returns, destroying the only pointer ...
    (microsoft.public.vc.language)
  • Re: realloc() implicit free() ?
    ... >>> If realloc() finds it necessary to move the memory block, ... > malloc implementations already out there. ... malloc allocates continious memeory i.e one Block while ...
    (comp.lang.c)