Re: when can realloc fail?
- From: "Malcolm McLean" <regniztar@xxxxxxxxxxxxxx>
- Date: Sun, 1 Apr 2007 23:42:15 +0100
<banansol@xxxxxxxxxxxx> wrote in message
Hi,It is a bit of a grey area.
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?
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
.
- References:
- when can realloc fail?
- From: banansol
- when can realloc fail?
- Prev by Date: Re: Reading a key inside a loop
- Next by Date: Re: The weird while and If
- Previous by thread: Re: when can realloc fail?
- Next by thread: Re: question about k&r2
- Index(es):
Relevant Pages
|