Right, if we were to implement the simplest (but not the most efficient) form of realloc, it would look something like this:
Code:
void *myrealloc(void *oldptr, size_t newsize)
{
size_t oldsize = magicalFindSize(oldblock); /* See comment below */
void *newptr;
if (newsize != oldsize)
{
newptr = malloc(newsize);
if (newptr != NULL)
{
memcpy(newptr, oldptr, MIN(oldsize, newsize));
free(oldptr);
}
return newptr;
}
/* No size change, so no need to change the allocation */
return oldptr;
}
The function "magicalFindSize" will dig out the "admin" block for this allocation, and find out what size the block is. It's not really important.
What is important is the bit in red: The freeing of the original pointer. If that pointer wasn't originally from a malloc/realloc call, then things are going to go horribly wrong at some point sooner or later [quite possibly LATER].
A real realloc will have some more logic in it, where it looks to see if there is more space right behind the current allocation that we can use directly, rather than doing a complete new allocation, and such things - but that doesn't change the matter that sooner or later the original allocation will most likely be freed.
--
Mats