From: solar <> Date: Thu, 9 Feb 2006 05:11:43 +0000 (+0000) Subject: Bug #1 - realloc( NULL, size ) fails. Fixed. X-Git-Url: https://pd.if.org/git/?p=pdclib.old;a=commitdiff_plain;h=7325dfda3e33fd4a3fcd5f925446cebd68b1a53d Bug #1 - realloc( NULL, size ) fails. Fixed. --- diff --git a/functions/stdlib/malloc.c b/functions/stdlib/malloc.c index c767b17..a97730f 100644 --- a/functions/stdlib/malloc.c +++ b/functions/stdlib/malloc.c @@ -20,6 +20,7 @@ #endif /* TODO: Primitive placeholder. Much room for improvement. */ +/* TODO: Leaves nodes with size < _PDCLIB_MINALLOC, which are never assigned */ /* Keeping pointers to the first and the last element of the free list. */ struct _PDCLIB_headnode_t _PDCLIB_memlist = { NULL, NULL }; @@ -163,7 +164,7 @@ int main( int argc, char * argv[] ) BEGIN_TESTS; #ifndef REGTEST { - void * ptr1, * ptr2, * ptr3, * ptr4, * ptr5, * ptr6, * ptr7, * ptr8; + void * ptr1, * ptr2, * ptr3, * ptr4, * ptr5, * ptr6, * ptr7, * ptr8, * ptr9; char * pages_start = _PDCLIB_allocpages( 0 ); /* allocating 10 byte; expected: 1 page allocation, node split */ TESTCASE( MEMTEST( ptr1, 10 ) ); @@ -213,6 +214,11 @@ int main( int argc, char * argv[] ) free( ptr8 ); TESTCASE( MEMTEST( ptr8, EFFECTIVE + 1 - _PDCLIB_MINALLOC - sizeof( struct _PDCLIB_memnode_t ) ) ); TESTCASE( PAGETEST( 9 ) ); + /* realloc with NULL pointer; expected: no page allocation, no node split */ + ptr9 = realloc( NULL, 4072 ); + TESTCASE( ptr9 != NULL ); + TESTCASE( memset( ptr9, 0, 4072 ) == ptr9 ); + TESTCASE( PAGETEST( 9 ) ); } #endif return TEST_RESULTS; diff --git a/functions/stdlib/realloc.c b/functions/stdlib/realloc.c index df5fca1..90214e0 100644 --- a/functions/stdlib/realloc.c +++ b/functions/stdlib/realloc.c @@ -18,6 +18,11 @@ void * realloc( void * ptr, size_t size ) { + if ( ptr == NULL ) + { + return malloc( size ); + } + { struct _PDCLIB_memnode_t * baseptr = (struct _PDCLIB_memnode_t *)( (char *)ptr - sizeof( struct _PDCLIB_memnode_t ) ); if ( baseptr->size >= size ) { @@ -30,6 +35,7 @@ void * realloc( void * ptr, size_t size ) free( ptr ); return newptr; } + } return NULL; }