Eine Implementierung von realloc()
kann in etwa wie folgt aussehen:
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;
}
Bitte beachte, dass ich mit malloc_
hier beginnen mehrere Funktionen mit Namen nenne. Diese Funktionen existieren (nach bestem Wissen) in keiner Implementierung; Sie sind als Platzhalter gedacht, aber der Zuordner führt diese Aufgaben tatsächlich intern aus.
Da die Implementierung von realloc()
von diesen internen Tools abhängt, ist ihre Implementierung vom Betriebssystem abhängig. Die Schnittstelle ist jedoch universell.
+1 für 'mremap/MREMAP_MAYMOVE'. – edmz