aboutsummaryrefslogtreecommitdiffstats
path: root/src/pdclib/functions/stdlib/realloc.c
blob: cbc01d4bb74ee33ffd930a056119a69dc0cf7606 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* void * realloc( void *, size_t )

   This file is part of the Public Domain C Library (PDCLib).
   Permission is granted to use, modify, and / or redistribute at will.
*/

#include <stdlib.h>
#include <string.h>
#include <stddef.h>

#ifndef REGTEST

/* TODO: Primitive placeholder. Improve. */

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 )
        {
            /* 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 );
        }
    }
    free( ptr );
    return newptr;
}

#endif

#ifdef TEST

#include "_PDCLIB_test.h"

int main( void )
{
    /* tests covered in malloc test driver */
    return TEST_RESULTS;
}

#endif