]> git.sur5r.net Git - cc65/blob - libsrc/common/realloc.c
32c05f46f8dbac520051accea1e41b6c6077ef4f
[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         memcpy (newblock, block, oldsize - 2);
66         free (block);
67     }
68     return newblock;
69 }
70
71
72
73
74
75
76
77
78