This code is from books K and R - Chapter 8 Section 7: Example - Storage Assistant. This code, at least for me, makes no sense. A βheaderβ is a combination of structure and βthe most restrictive type of alignment,β which is a long type. Malloc will then find a sufficiently large free space with a size that is a multiple of the size of the header.
static Header base; static Header *freep = NULL; void *malloc(unsigned nbytes) { Header *p, *prevp; Header *morecore(unsigned); unsigned nunits; nunits = (nbytes+sizeof(Header)-1)/sizeof(Header) + 1; if ((prevp = freep) == NULL) { base.s.ptr = freeptr = prevptr = &base; base.s.size = 0; } for (p = prevp->s.ptr; ; prevp = p, p = p->s.ptr) { if (p->s.size >= nunits) { if (p->s.size == nunits) prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; p += p->s.size; p->s.size = nunits; } freep = prevp; return (void *)(p+1); } if (p == freep) if ((p = morecore(nunits)) == NULL) return NULL; } }
The odd part of this code is the operator nunits = (nbytes+sizeof(Header)-1)/sizeof(Header) + 1;
, which is then used when comparing if (p->s.size >= nunits)
to find a sufficiently large space with units in terms of the size of the header. Should the first be only nunits = (nbytes+sizeof(Header)) / sizeof(Header)
? The source code will evaluate a value less than it should be. What is + -1? Why allocate less space than required.
source share