X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=functions%2Fstdlib%2Frealloc.c;h=a7cc395d21a9f39d3669e4c7f4637c13f643c451;hb=b1fc26afebd4d557ff89a44bc21767a8704c3809;hp=c1ba38f4d1cd2b674aa0ae5013ff0ebf54070379;hpb=b08f4b52b1cd1f7a9553c0f357a7c90859fa3e73;p=pdclib diff --git a/functions/stdlib/realloc.c b/functions/stdlib/realloc.c index c1ba38f..a7cc395 100644 --- a/functions/stdlib/realloc.c +++ b/functions/stdlib/realloc.c @@ -1,5 +1,3 @@ -/* $Id$ */ - /* void * realloc( void *, size_t ) This file is part of the Public Domain C Library (PDCLib). @@ -16,25 +14,31 @@ void * realloc( void * ptr, size_t size ) { + void * newptr = NULL; if ( ptr == NULL ) { return malloc( size ); } + if ( size > 0 ) { - struct _PDCLIB_memnode_t * baseptr = (struct _PDCLIB_memnode_t *)( (char *)ptr - sizeof( struct _PDCLIB_memnode_t ) ); - if ( baseptr->size >= size ) - { - return ptr; - } - else - { - void * newptr = malloc( size ); - memcpy( newptr, ptr, baseptr->size ); - free( ptr ); - return newptr; - } + struct _PDCLIB_memnode_t * baseptr = (struct _PDCLIB_memnode_t *)( (char *)ptr - sizeof( struct _PDCLIB_memnode_t ) ); + if ( baseptr->size >= size ) + { + /* Current memnode is large enough; nothing to do. */ + return ptr; + } + else + { + /* Get larger memnode and copy over contents. */ + if ( ( newptr = malloc( size ) ) == NULL ) + { + return NULL; + } + memcpy( newptr, ptr, baseptr->size ); + } } - return NULL; + free( ptr ); + return newptr; } #endif @@ -49,3 +53,4 @@ int main( void ) } #endif +