Re: realloc(): invalid next size
- From: "Rod Pemberton" <do_not_have@xxxxxxxxxxxxxxxxx>
- Date: Tue, 11 Apr 2006 20:25:07 -0400
"Chris Torek" <nospam@xxxxxxxxx> wrote in message
news:e1gq3i0930@xxxxxxxxxxxxxxxxxxxx
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;
}
Hmm, no NULL check for old?
<snip>
(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)?)
If your question wasn't rhetorical, this realloc probably answers your
question. It has undefined behavior since it doesn't determine the 'magic
mystery size' of s1...
void *my_realloc (void *s1, size_t size)
{
void *s2=NULL;
if (size!=0||s1==NULL)
s2 = malloc(size);
else
free(s1);
if (s1!=NULL)
memcpy(s2, s1, size);
return(s2);
}
Rod Pemberton
.
- Follow-Ups:
- Re: realloc(): invalid next size
- From: Chris Torek
- 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
- Re: realloc(): invalid next size
- From: Chris Torek
- realloc(): invalid next size
- Prev by Date: Re: life cycle
- Next by Date: Re: life cycle
- Previous by thread: Re: realloc(): invalid next size
- Next by thread: Re: realloc(): invalid next size
- Index(es):
Relevant Pages
|