]> git.sur5r.net Git - cc65/blob - libsrc/common/free.c
This commit was generated by cvs2svn to compensate for changes in r2,
[cc65] / libsrc / common / free.c
1 /*
2  * free.c
3  *
4  * Ullrich von Bassewitz, 11.08.1998
5  */
6
7
8
9 #include <stdlib.h>
10 #include "_heap.h"
11
12
13
14 void free (void* block)
15 /* Release an allocated memory block. The function will accept NULL pointers
16  * (and do nothing in this case).
17  */
18 {
19     unsigned* b;
20     unsigned size;
21     struct freeblock* f;
22
23
24     /* Allow NULL arguments */
25     if (block == 0) {
26         return;
27     }
28
29     /* Get a pointer to the real memory block, then get the size */
30     b = (unsigned*) block;
31     size = *--b;
32
33     /* Check if the block is at the top of the heap */
34     if (((int) b) + size == (int) _hptr) {
35
36         /* Decrease _hptr to release the block */
37         _hptr = (unsigned*) (((int) _hptr) - size);
38
39         /* Check if the last block in the freelist is now at heap top. If so,
40          * remove this block from the freelist.
41          */
42         if (f = _hlast) {
43             if (((int) f) + f->size == (int) _hptr) {
44                 /* Remove the last block */
45                 _hptr = (unsigned*) (((int) _hptr) - f->size);
46                 if (_hlast = f->prev) {
47                     /* Block before is now last block */
48                     f->prev->next = 0;
49                 } else {
50                     /* The freelist is empty now */
51                     _hfirst = 0;
52                 }
53             }
54         }
55
56     } else {
57
58         /* Not at heap top, enter the block into the free list */
59         _hadd (b, size);
60
61     }
62 }
63
64
65