X-Git-Url: https://pd.if.org/git/?a=blobdiff_plain;f=functions%2Fstdlib%2Frealloc.c;h=a7cc395d21a9f39d3669e4c7f4637c13f643c451;hb=b1fc26afebd4d557ff89a44bc21767a8704c3809;hp=93a2aa418d2280d0853bf7cae2ee474abd8b0081;hpb=1d9d92ba957a0b8307c9a65c35867fde68e6533b;p=pdclib diff --git a/functions/stdlib/realloc.c b/functions/stdlib/realloc.c index 93a2aa4..a7cc395 100644 --- a/functions/stdlib/realloc.c +++ b/functions/stdlib/realloc.c @@ -1,71 +1,56 @@ -/* ---------------------------------------------------------------------------- - * $Id$ - * ---------------------------------------------------------------------------- - * Public Domain C Library - http://pdclib.sourceforge.net - * This code is Public Domain. Use, modify, and redistribute at will. - * --------------------------------------------------------------------------*/ +/* void * realloc( void *, size_t ) -void * realloc( void * ptr, size_t size ) { /* TODO */ }; + This file is part of the Public Domain C Library (PDCLib). + Permission is granted to use, modify, and / or redistribute at will. +*/ -/* PDPC code - assumes size_t of memory chunk at offset -4. -{ - char * newptr; - size_t oldsize; +#include +#include +#include - if ( ( newptr = malloc(size) ) != NULL ) - { - if ( ptr != NULL ) - { - // reading size information from hidden chunk header - oldsize = * (size_t *) ( (char *) ptr - 4 ); - // correctly handle *down*sizing as well as *up*sizing - memcpy( newptr, ptr, ( oldsize < size ) ? oldsize : size ); - free( ptr ); - } - } - return ( newptr ); -} -*/ +#ifndef REGTEST + +/* TODO: Primitive placeholder. Improve. */ -/* Thomas "Beyond Infinity" Kreitner's code - unchecked, unoptimized +void * realloc( void * ptr, size_t size ) { - uint_t found = 0; - uint_t length; - chunk_t * new; - chunk_t * chunk; - // searching the block to-be-allocated - chunk = used_mem.start; - while ( ! found && ( chunk->next != NULL ) + void * newptr = NULL; + if ( ptr == NULL ) { - if ( chunk->address == ptr ) - { - found++; - } - else - { - chunk=chunk->next; - } + return malloc( size ); } - if ( found ) + if ( size > 0 ) { - length = chunk->length; - // allocate new memory area - if ( ( new = (void *) malloc( size ) ) != NULL ) + struct _PDCLIB_memnode_t * baseptr = (struct _PDCLIB_memnode_t *)( (char *)ptr - sizeof( struct _PDCLIB_memnode_t ) ); + if ( baseptr->size >= size ) { - // copy the data - memcpy( ptr, new, length ); - // release the old memory - free( ptr ); + /* Current memnode is large enough; nothing to do. */ + return ptr; } else { - new = NULL; + /* Get larger memnode and copy over contents. */ + if ( ( newptr = malloc( size ) ) == NULL ) + { + return NULL; + } + memcpy( newptr, ptr, baseptr->size ); } } - else - { - new = NULL; - } - return new; + free( ptr ); + return newptr; } -*/ + +#endif + +#ifdef TEST +#include <_PDCLIB_test.h> + +int main( void ) +{ + /* tests covered in malloc test driver */ + return TEST_RESULTS; +} + +#endif +