Re: realloc(): invalid next size
- From: Chris Torek <nospam@xxxxxxxxx>
- Date: 11 Apr 2006 17:47:30 GMT
Michael Wojcik wrote:
The result of realloc should always be stored in a temporary
variable and should be checked for null. If it is null, remember
to free the old value ...
In article <slrne3nmnj.c3j.hexkid@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
Pedro Graca <hexkid@xxxxxxxxxx> wrote:
Uh? Doesn't realloc(), when it doesn't fail, call free() all by itself
if there's a need for that?
No!
With a few exceptions (noted below), realloc() is essentially an
optimized version of the following:
void *realloc(void *old, size_t newsize) {
size_t oldsize = __some_sort_of_magic_done_here(old);
void *new;
new = malloc(newsize);
if (new != NULL) {
memcpy(new, old, oldsize < newsize ? oldsize : newsize);
free(old);
}
return new;
}
(where the "magic" function obtains the size previously malloc()ed,
or the size of the previously malloc()ed region, whichever is
larger, based on "old", or returns 0 if old==NULL).
Note specifically that "old" is *not*, I repeat NOT, free()d if
"new" memory is not obtainable.
Also suppose the reallocated memory doesn't 'move' (newkey == key);
In this case, the return value from realloc() is necessarily not
NULL (well, except if old==NULL).
In both C89 and C99, realloc(p, 0) (where p!=NULL) is equivalent
to free(p). In at least C89 (and perhaps both C89 and C99),
realloc(NULL, 0) does something no one can quite explain. :-)
(Seriously: C89 specifically said that realloc(NULL,n) was equivalent
to malloc(n), and malloc(0) *could* be equivalent to malloc(1); it
then also said that realloc(p,0) was equivalent to free(p); so what
then is realloc(NULL,0) -- is it like malloc(0) and hence like
malloc(1), or is it just free(NULL)?)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
.
- Follow-Ups:
- Re: realloc(): invalid next size
- From: Rod Pemberton
- Re: realloc(): invalid next size
- From: Pedro Graca
- Re: realloc(): invalid next size
- References:
- realloc(): invalid next size
- From: Deephay
- Re: realloc(): invalid next size
- From: Michael Wojcik
- Re: realloc(): invalid next size
- From: Pedro Graca
- realloc(): invalid next size
- Prev by Date: Re: Some Questions
- Next by Date: Re: pgm without std library functions
- Previous by thread: Re: realloc(): invalid next size
- Next by thread: Re: realloc(): invalid next size
- Index(es):
Relevant Pages
|