Re: realloc(): invalid next size




"Pedro Graca" <hexkid@xxxxxxxxxxx> wrote in message
news:slrne3qlvp.c3j.hexkid@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Rod Pemberton wrote:
"Pedro Graca" <hexkid@xxxxxxxxxxx> wrote in message
news:slrne3q03s.c3j.hexkid@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Right. Let's run "my_realloc(valid_old_pointer, 0);" step by step ...

void *my_realloc (void *s1, size_t size)
{
void *s2=NULL;
/* s1 --> valid_old_pointer
* s2 --> NULL
* size --> 0 */

if (size!=0||s1==NULL)
s2 = malloc(size);
else
free(s1);
/* s1 --> free'd valid_old_pointer
* s2 --> NULL
* size --> 0 */


Correct to here.

if (s1!=NULL)
memcpy(s2, s1, size);
/* And here we go ...

No we don't. s1!=NULL is true. This if() is skipped. s1 is freed, but is
_NOT_ NULL. It retains it's prior value. Why? Because, the argument to
free() is passed by value. That means s1 isn't changed.

free() is declared as:
void free(void *ptr);

For free() to return a NULL as you seem to think, it'd need to be declared
as (this would also change the way it is called):
void free(void **ptr);

HTH,
Rod Pemberton


.