





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






CMSC 212 – F05 (lect 16)^1
CMSC 212 – F05 (lect 16)^2
CMSC 212 – F05 (lect 16)^3
CMSC 212 – F05 (lect 16)^4
CMSC 212 – F05 (lect 16)^7
CMSC 212 – F05 (lect 16)^8
#include <stdio.h> #include <unistd.h>
typedef struct _header { unsigned int size:29; unsigned int unusedBits:2; unsigned int allocated:1; struct _header *prev; } header;
#define HEAP_INCR (1024 * 1024) static header *heap;
void mm_init() { header *end; heap = (header ) sbrk(HEAP_INCR ); heap->size = (HEAP_INCR- (2sizeof(header)))>>3; heap->allocated = 0; heap->prev = NULL;
end = heap + heap->size - 1; end->allocated = 0; end->size = 0; end->prev = heap;
CMSC 212 – F05 (lect 16)^9
void *mm_alloc(unsigned int size) { header *curr, *temp, next; if (!heap) mm_init(); for (curr=heap;; curr = curr + curr->size + 1) { if (curr->size >= size && !curr->allocated) { temp = curr + ((size + 7) >> 3) + 1; next = curr + curr->size + 1; if (temp < (next - 1)) { / split current node */ temp->size = next - temp - 1; temp->allocated = 0; temp->prev = curr; next->prev = temp; curr->size = temp - curr - 1; curr->allocated = 1; } return ((void *)(curr + 1));
CMSC 212 – F05 (lect 16)^10
} else if (!curr->size) { /* no room in the heap, grow heap */ temp = (header ) sbrk(HEAP_INCR); if (!temp) return NULL; curr->size = (HEAP_INCR- sizeof(header))>>3; curr->allocated = 0; / update new end */ } } }
CMSC 212 – F05 (lect 16)^13
CMSC 212 – F05 (lect 16)^14
CMSC 212 – F05 (lect 16)^15
Not-reachable (garbage) Reachable^ variables (Inside the program)
CMSC 212 – F05 (lect 16)^16
void mark(ptr p) { ptr b; b = isPtr(p); if (!b) return; if (b->marked) return; b->marked = 1; for (i=0; i < b->size; i++) { mark(b + i + 1); } }