An implementation of realloc()
may look something like the following:
void * realloc(void *ptr, size_t size)
{
// realloc() on a NULL pointer is the same as malloc().
if (ptr == NULL)
return malloc(size);
size_t oldsize = malloc_getsize(ptr);
// Are we shrinking an allocation? That's easy.
if (size < oldsize) {
malloc_setsize(ptr, size);
return ptr;
}
// Can we grow this allocation in place?
if (malloc_can_grow(ptr, size)) {
malloc_setsize(ptr, size);
return ptr;
}
// Create a new allocation, move the data there, and free the old one.
void *newptr = malloc(size);
if (newptr == NULL)
return NULL;
memcpy(newptr, ptr, oldsize);
free(ptr);
return newptr;
}
Note that I'm calling several functions with names starting with malloc_
here. These functions don't actually exist (to the best of my knowledge) in any implementation; they're intended as placeholders for however the allocator actually performs these tasks internally.
Since the implementation of realloc()
depends on these internal tools, its implementation is OS-dependent. However, the realloc()
interface is universal.
size
argument is lower than in the previous call. – Ioves