Micron Document
The C Programming Language, Ansi C


← Prev · 194/277 · Next →

/* free: put block ap in free list */
void free(void *ap)
{
Header *bp, *p;

bp = (Header *)ap - 1; /* point to block header */
for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
if (p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break; /* freed block at start or end of arena */

if (bp + bp->size == p->s.ptr) { /* join to upper nbr */
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
if (p + p->size == bp) { /* join to lower nbr */
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
freep = p;
}

Although storage allocation is intrinsically machine-dependent, the code above
illustrates how the machine dependencies can be controlled and confined to a
very small part of the program. The use of

typedef

and

union

handles alignment (given that

sbrk

supplies an appropriate pointer).
Casts arrange that pointer conversions are made explicit, and even cope with a
badly-designed system interface. Even though the details here are related to
storage allocation, the general approach is applicable to other situations as
well.

Exercise 8-6. The standard library function calloc(n,size) returns a pointer to n objects of size size, with the storage initialized to zero. Write calloc, by calling malloc or by modifying it.

Exercise 8-7. malloc accepts a size request without checking its plausibility; free believes that the block it is asked to free contains a valid size field. Improve these routines so they make more pains with error checking.

Exercise 8-8. Write a routine bfree(p,n) that will free any arbitrary block p of n characters into the free list maintained by malloc and free. By using bfree, a user can add a static or external array to the free list at any time.




Compiled by tmdcjsl(skidrow8123@hotmail.com)