]> pd.if.org Git - pdclib/blob - functions/stdlib/realloc.c
Fixed size==0 bug pointed out by Rod P.
[pdclib] / functions / stdlib / realloc.c
1 /* $Id$ */
2
3 /* void * realloc( void *, size_t )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #include <stdlib.h>
10 #include <string.h>
11 #include <stddef.h>
12
13 #ifndef REGTEST
14
15 /* TODO: Primitive placeholder. Improve. */
16
17 void * realloc( void * ptr, size_t size )
18 {
19     void * newptr = NULL;
20     if ( ptr == NULL )
21     {
22         return malloc( size );
23     }
24     if ( size > 0 )
25     {
26         struct _PDCLIB_memnode_t * baseptr = (struct _PDCLIB_memnode_t *)( (char *)ptr - sizeof( struct _PDCLIB_memnode_t ) );
27         if ( baseptr->size >= size )
28         {
29             /* Current memnode is large enough; nothing to do. */
30             return ptr;
31         }
32         else
33         {
34             /* Get larger memnode and copy over contents. */
35             newptr = malloc( size );
36             memcpy( newptr, ptr, baseptr->size );
37         }
38     }
39     free( ptr );
40     return newptr;
41 }
42
43 #endif
44
45 #ifdef TEST
46 #include <_PDCLIB_test.h>
47
48 int main( void )
49 {
50     /* tests covered in malloc test driver */
51     return TEST_RESULTS;
52 }
53
54 #endif