/* coalesce free blocks */
static void *coalesce(void *bp){
   
    size_t prevAllocBit = getPrevAlloc(getHeader(bp));
    size_t nextAllocBit = getAlloc(getHeader(nextBlock(bp)));
    size_t size = getSize(getHeader(bp));
    size_t index;
    size_t prevPAlloc;

    /* both the previous and next block allocated */
    if (prevAllocBit && nextAllocBit) {
        setPrevFree(getHeader(nextBlock(bp)));
    }

    /* Only previous block is free */
    else if (!prevAllocBit && nextAllocBit) {
        size += getSize(getHeader(prevBlock(bp)));
        prevPAlloc = getPrevAlloc(getHeader(prevBlock(bp)));
        deleteListNode(prevBlock(bp));
        put(getFooter(bp), size);
        bp = prevBlock(bp);
        put(getHeader(bp), pack(size, prevPAlloc, 0));
        setPrevFree(getHeader(nextBlock(bp)));
    }

    /* Only next block is free */
    else if (prevAllocBit && !nextAllocBit) {
        size += getSize(getHeader(nextBlock(bp)));
        deleteListNode(nextBlock(bp));
        put(getHeader(bp), pack(size, prevAllocBit, 0));
        put(getFooter(bp), size);
    }
    
    /* Both previous and next block are free */
    else {
        size += getSize(getHeader(prevBlock(bp))) + 
            getSize(getFooter(nextBlock(bp)));
        prevPAlloc = getPrevAlloc(getHeader(prevBlock(bp)));
        deleteListNode(nextBlock(bp));
        deleteListNode(prevBlock(bp));
        put(getHeader(prevBlock(bp)), pack(size, prevPAlloc, 0));
        put(getFooter(nextBlock(bp)), size);
        bp = prevBlock(bp);
    }

    index = getIndex(size);
    insertListNode(bp, index);
    return bp;
}
/* Place a block to bp. If bp is larger than asize by more than the minimum
   block size, then split the block into two part, otherwize just set 
   the whole block allocated
*/
static void place(void *bp, size_t asize){
    size_t csize = getSize(getHeader(bp));
    size_t prevAllocBit = getPrevAlloc(getHeader(bp));
    size_t index;

    deleteListNode(bp);

    // Split the block
    if ((csize - asize) >= (2 * DSIZE)) {
        // Allocate the first part
        put(getHeader(bp), pack(asize, prevAllocBit, 1));

        // Set the remaining part free
        bp = nextBlock(bp);
        put(getHeader(bp), pack((csize - asize), prevAllocBit, 0));
        put(getFooter(bp), pack((csize - asize), 0, 0));
        // Insert the free part into free list
        index = getIndex(csize - asize);
        insertListNode(bp, index);
    }
    // No split
    else{
        put(getHeader(bp), pack(csize, prevAllocBit, 1));
        setPrevAlloc(getHeader(nextBlock(bp)));
    }
}
Example #3
0
ElemType pop(Stack * stack){
	ElemType x = NULL; 
	ListNode * node;
	if(stack->size > 0){
		node = getFirst(stack->elem);
		x = node->data;
		deleteListNode(node);
		stack->size--;
	}
	return x;
}