You can find this code in the K & R C programming language:
void *malloc(unsigned nbytes) { Header *p, *prevp; Header *moreroce(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; } }
(from http://pelusa.fis.cinvestav.mx/tmatos/LaSumA/LaSumA2_archivos/Supercomputo/The_C_Programming_Language.pdf )
Basically there is a linked list, and each node in the list starts with a heading indicating the next node, and the amount of memory that the node allocated after the heading (in multiples of the size of the heading). This linked list keeps track of where there is free memory.
What I don't understand is why the line in STRANGE LINE ????? necessary. I understand the first two. We want to give the user node the end, so we reduce the size and push p with the new size and give it to the user (+1). But then the third line wants to set the space size p points to the number of units. What for? After the second line of p points to a spot in free memory that does not seem to make any difference. Is this some kind of dodgy optimization that I donโt know about, or is it really necessary?
Thanks for any help!
c malloc memory
bombax
source share