Re: realloc(): invalid next size




"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


.



Relevant Pages

  • Re: Is realloc good form ?
    ... // Do something from Array to Transformed ... does the call to realloc wastes time then? ... if (Size!= OldSize) ... int Newsize = Size - 1; ...
    (comp.lang.c)
  • Re: realloc(): invalid next size
    ... void *realloc(void *old, size_t newsize) { ... memcpy(new, old, oldsize < newsize? ... ambiguity is intentional, to allow different implementations to do ...
    (comp.lang.c)
  • Re: Buffer growing strategy?
    ... I'm looking into a buffer ... newsize = oldsize * FACTOR; ... A very simple solution is to just call realloc for the new size ...
    (comp.lang.c)
  • Re: Is realloc good form ?
    ... void Func{ ... // Do something from Array to Transformed ... does the call to realloc wastes time then? ... if (Size!= OldSize) ...
    (comp.lang.c)
  • Re: realloc(): invalid next size
    ... void *realloc(void *old, size_t newsize) { ... memcpy(new, old, oldsize < newsize? ... Reading email is like searching for food in the garbage, ...
    (comp.lang.c)