Micron Document
The C Programming Language, Ansi C


← Prev · 193/277 · Next →

.

The UNIX system call sbrk(n) returns a pointer to n more bytes of storage. sbrk returns -1 if there was no space, even though NULL could have been a better design. The -1 must be cast to char * so it can be compared with the return value. Again, casts make the function relatively immune to the details of pointer representation on different machines. There is still one assumption, however, that pointers to different blocks returned by sbrk can be meaningfully compared. This is not guaranteed by the standard, which permits pointer comparisons only within an array. Thus this version of malloc is portable only among machines for which general pointer comparison is meaningful.


/* morecore: ask system for more memory */
static Header *morecore(unsigned nu)
{
char *cp, *sbrk(int);
Header *up;

if (nu < NALLOC)
nu = NALLOC;
cp = sbrk(nu * sizeof(Header));
if (cp == (char *) -1) /* no space at all */
return NULL;
up = (Header *) cp;
up->s.size = nu;
free((void *)(up+1));
return freep;
}

free

itself is the last thing. It scans the free list, starting at

freep

, looking for the place to insert the free block. This is
either between two existing blocks or at the end of the list. In any case, if
the block being freed is adjacent to either neighbor, the adjacent blocks are
combined. The only troubles are keeping the pointers pointing to the right
things and the sizes correct.