X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=functions%2Fstdlib%2Frealloc.c;h=099ad5dd170ea1251c4562d62bf70a295102bcc6;hb=5bf06fe94c113d389ff58afbc7e94d836e18db08;hp=67133b4a790747926a71accabc4d92df32700c25;hpb=d02f38605b53cdff5460cc6b9e1b2a80c3a2ba4c;p=pdclib diff --git a/functions/stdlib/realloc.c b/functions/stdlib/realloc.c index 67133b4..099ad5d 100644 --- a/functions/stdlib/realloc.c +++ b/functions/stdlib/realloc.c @@ -1,7 +1,5 @@ /* $Id$ */ -/* Release $Name$ */ - /* void * realloc( void *, size_t ) This file is part of the Public Domain C Library (PDCLib). @@ -18,25 +16,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 @@ -51,3 +55,4 @@ int main( void ) } #endif +