Dynamic Memory AllocationNovember 2, 2000Topics• Simple explicit allocators• Data structures• Mechanisms• Policiesclass20.ppt15-213“The course that gives CMU its Zip!”CS 213 F’00– 2 –class20.pptHarsh Reality #3Memory MattersMemory is not unbounded• It must be allocated and managed• Many applications are memory dominated–Especially those based on complex, graph algorithmsMemory referencing bugs especially pernicious• Effects are distant in both time and spaceMemory performance is not uniform• Cache and virtual memory effects can greatly affect programperformance• Adapting program to characteristics of memory system can lead tomajor speed improvementsCS 213 F’00– 3 –class20.pptDynamic Memory AllocationExplicit vs. Implicit Memory Allocator• Explicit: application allocates and frees space–E.g., malloc and free in C• Implicit: application allocates, but does not free space–E.g. garbage collection in Java, ML or LispAllocation• In both cases the memory allocator provides an abstraction ofmemory as a set of blocks• Doles out free memory blocks to applicationWill discuss simple explicit memory allocation todayApplicationDynamic Memory AllocatorHeap MemoryCS 213 F’00– 4 –class20.pptProcess memory imagekernel virtual memoryMemory mapped region forshared librariesrun-time heap (via malloc)program text (.text)initialized data (.data)uninitialized data (.bss)stack0%espmemory invisible to user codethe “brk” ptrAllocators requestadditional heapmemoryfrom the operatingsystemusing the sbrk()function.CS 213 F’00– 5 –class20.pptMalloc package#include <stdlib.h>void *malloc(size_t size)• if successful:–returns a pointer to a memory block of at least size bytes, aligned to8-byte boundary.–if size==0, returns NULL• if unsuccessful: returns NULLvoid free(void *p)• returns the block pointed at by p to pool of available memory• p must come from a previous call to malloc or realloc.void *realloc(void *p, size_t size)• changes size of block p and returns ptr to new block.• contents of new block unchanged up to min of old and new size.CS 213 F’00– 6 –class20.pptMalloc examplevoid foo(int n, int m) { int i, *p; /* allocate a block of n ints */ if ((p = (int *) malloc(n * sizeof(int))) == NULL) { perror("malloc"); exit(0); } for (i=0; i<n; i++) p[i] = i; /* add m bytes to end of p block */ if ((p = (int *) realloc(p, (n+m) * sizeof(int))) == NULL) { perror("realloc"); exit(0); } for (i=n; i < n+m; i++) p[i] = i; /* print new array */ for (i=0; i<n+m; i++) printf("%d\n", p[i]); free(p); /* return p to available memory pool */}CS 213 F’00– 7 –class20.pptAssumptionsAssumptions made in this lecture• memory is word addressed (each word can hold a pointer)Allocated block(4 words)Free block(3 words)Free wordAllocated wordCS 213 F’00– 8 –class20.pptAllocation examplesp1 = malloc(4)p2 = malloc(5)p3 = malloc(6)free(p2)p4 = malloc(2)CS 213 F’00– 9 –class20.pptConstraintsApplications:• Can issue arbitrary sequence of allocation and free requests• Free requests must correspond to an allocated blockAllocators• Can’t control number or size of allocated blocks• Must respond immediately to all allocation requests–i.e., can’t reorder or buffer requests• Must allocate blocks from free memory–i.e., can only place allocated blocks in free memory• Must align blocks so they satisfy all alignment requirements–usually 8 byte alignment• Can only manipulate and modify free memory• Can’t move the allocated blocks once they are allocated–i.e., compaction is not allowedCS 213 F’00– 10 –class20.pptGoals of good malloc/free Primary goals• Good time performance for malloc and free–Ideally should take constant time (not always possible)–Should certainly not take linear time in the number of blocks• Good space utilization–User allocated structures should be large fraction of the heap.–want to minimize “fragmentation”.Some other goals• Good locality properties–structures allocated close in time should be close in space–“similar” objects should be allocated close in space• Robust–can check that free(p1) is on a valid allocated object p1–can check that memory references are to allocated spaceCS 213 F’00– 11 –class20.pptPerformance goals: throughputGiven some sequence of malloc and free requests:• R0, R1, ..., Rk, ... , Rn-1Want to maximize throughput and peak memoryutilization.• These goals are often conflictingThroughput:• Number of completed requests per unit time• Example:–5,000 malloc calls and 5,000 free calls in 10 seconds–throughput is 1,000 operations/second.CS 213 F’00– 12 –class20.pptPerformance goals: peak memory utilizationGiven some sequence of malloc and free requests:• R0, R1, ..., Rk, ... , Rn-1Def: aggregate payload Pk:• malloc(p) results in a block with a payload of p bytes..• After request Rk has completed, the aggregate payload Pk is the sum ofcurrently allocated payloads.Def: current heap size is denoted by Hk• Note that Hk is monotonically nondecreasingDef: peak memory utilization:• After k requests, peak memory utilization is:–Uk = ( maxi<k Pi ) / HkCS 213 F’00– 13 –class20.pptInternal FragmentationPoor memory utilization caused by fragmentation.• Comes in two forms: internal and external fragmentationInternal fragmentation• For some block, internal fragmentation is the difference between theblock size and the payload size.• Caused by overhead of maintaining heap data structures, paddingfor alignment purposes, or explicit policy decisions (e.g., not to splitthe block).• Depends only on the pattern of previous requests, and thus is easyto measure.payloadInternal fragmentationblockInternal fragmentationCS 213 F’00– 14 –class20.pptExternal fragmentationp1 = malloc(4)p2 = malloc(5)p3 = malloc(6)free(p2)p4 = malloc(6)oops!Occurs when there is enough aggregate heap memory, but no singlefree block is large enoughExternal fragmentation depends on the pattern of future requests, andthus is difficult to measure.CS 213 F’00– 15 –class20.pptImplementation issues• How do we know how much memory to free just givena pointer?• How do we keep track of the free blocks?• What do we do with the extra space when allocating astructure that is smaller than the free block it isplaced in?• How do we pick a block to use for allocation -- manymight fit?• How do we
View Full Document