]> git.sur5r.net Git - cc65/blob - libsrc/common/realloc.c
Add ROM function defines
[cc65] / libsrc / common / realloc.c
1 /*
2  * realloc.c
3  *
4  * Ullrich von Bassewitz, 06.06.1998
5  */
6
7
8
9 #include <stdlib.h>
10 #include <string.h>
11 #include "_heap.h"
12
13
14
15 void* realloc (void* block, size_t size)
16 {
17     unsigned* b;
18     unsigned* newblock;
19     unsigned oldsize;
20     int diff;
21
22     /* Check the block parameter */
23     if (!block) {
24         /* Block is NULL, same as malloc */
25         return malloc (size);
26     }
27
28     /* Check the size parameter */
29     if (size == 0) {
30         /* Block is not NULL, but size is: free the block */
31         free (block);
32         return 0;
33     }
34
35     /* Make the internal used size from the given size */
36     size += HEAP_ADMIN_SPACE;
37     if (size < sizeof (struct freeblock)) {
38         size = sizeof (struct freeblock);
39     }
40
41     /* Get a pointer to the real block, get the old block size */
42     b = (unsigned*) (((int) block) - 2);
43     oldsize = *b;
44
45     /* Get the size difference as a signed quantity */
46     diff = size - oldsize;
47
48     /* Is the block at the current heap top? */
49     if (((int) b) + oldsize == ((int) _hptr)) {
50         /* Check if we've enough memory at the heap top */
51         int newhptr;
52         newhptr = ((int) _hptr) + diff;
53         if (newhptr <= ((int) _hend)) {
54             /* Ok, there's space enough */
55             _hptr = (unsigned*) newhptr;
56             *b = size;
57             return block;
58         }
59     }
60
61     /* The given block was not located on top of the heap, or there's no
62      * room left. Try to allocate a new block and copy the data.
63      */
64     if (newblock = malloc (size)) {
65
66         /* Adjust the old size to the user visible portion */
67         oldsize -= sizeof (unsigned);
68
69         /* If the new block is larger than the old one, copy the old 
70          * data only 
71          */
72         if (size > oldsize) {
73             size = oldsize;
74         }
75
76         /* Copy the block data */
77         memcpy (newblock, block, size);
78         free (block);
79     }
80     return newblock;
81 }
82
83
84