Presentation on theme: "Week 12 (March 28th) Outline Memory Allocation Lab 6 Reminders Lab 6: April 7 th (next Thurs) Start Early!!! Exam 2: April 5 th (Next Tue) TA: Kun Gao."— Presentation transcript:
Week 12 (March 28th) Outline Memory Allocation Lab 6 Reminders Lab 6: April 7 th (next Thurs) Start Early!!! Exam 2: April 5 th (Next Tue) TA: Kun Gao
Memory Allocation Overview Maintains heap as a collection of various sized blocks Each block contiguous chunk of virtual mem. Allocating memory Freeing memory
Dynamic Memory Allocation Do not know memory requirements beforehand Explicit allocators C standard library ‘malloc’ and ‘free’ Implicit allocators (garbage collection) Lisp, ML, Java
C ‘Malloc’ and ‘Free’ Malloc allocates using: mmap, munmap void *sbrk(int incr) double word aligned (8-bytes) Free: void free(void *ptr) *ptr must be a valid pointer returned by malloc
Allocator Requirements and Goals Constraints Handle arbitrary request sequences Making immediate responses to requests Using only the heap Aligning blocks Not modifying allocated blocks Goals Maximize throughput Maximize utilization
Placement Policy Best-Fit First-Fit Next-Fit No placement policy is perfect! Unless you know the future
Best Fit not always ‘Best’! 6 bytes free Memory in use4 bytes free Consider the following accesses (not counting header sizes): 1.malloc(3) 2.malloc(3) 3.malloc(4) First Fit will be able to allocate memory for all three. Best fit will not!
Example implementation Section 10.9.12 Understand every line of the code Implicit free list + immediate boundary tag coalescing + first fit Code is available at http://csapp.cs.cmu.edu/public/ics/code/vm/malloc.c Use it as a starting point
Block format Header Pointer returned by malloc (Block Pointer (bp)) 32 bits >= what user asked for in malloc Footer Payload
Header/footer format Double word alignment Why is size only 29 bits? Lower 3 bits a = 1: allocated, or a = 0: free Pack size and allocated bits into a single integer Size = 24 (0x18). Block is allocated Header = 0 x18 | 0x1 = 0x19 0 0 a size 3 2 1 0 31
Heap format 8|1 0|1 Double Word Alignment (8 bytes) 4 bytes Pad PrologueEpilogue Allocated and Free Blocks HDRFTRHDRFTR
Example Assume initial 4-byte padding, no prologue, both header and foot, and first fit Allocator starts at 0xA0000000 Malloc(1) = ? Malloc(2) = ?
Very useful macros #define WSIZE 4 Size of word #define DSIZE 8 Size of double word #define CHUNKSIZE (1<<12) Initial size of heap (for expanding) #define OVERHEAD 8 Extra bytes used by header and footer