Dynamic Memory Allocation INov 5, 2002Dynamic Memory Allocation INov 5, 2002TopicsTopicsn Simple explicit allocatorsl Data structuresl Mechanismsl Policiesclass21.ppt15-213“The course that gives CMU its Zip!”– 2 –15-213, F’02Harsh RealityHarsh RealityMemory MattersMemory MattersMemory is not unboundedMemory is not unboundedn It must be allocated and managedn Many applications are memory dominatedl Especially those based on complex, graph algorithmsMemory referencing bugs especially perniciousMemory referencing bugs especially perniciousn Effects are distant in both time and spaceMemory performance is not uniformMemory performance is not uniformn Cache and virtual memory effects can greatly affect programperformancen Adapting program to characteristics of memory system canlead to major speed improvements– 3 –15-213, F’02Dynamic Memory AllocationDynamic Memory AllocationExplicit vs. Implicit Memory Explicit vs. Implicit Memory AllocatorAllocatorn Explicit: application allocates and frees spacel E.g., malloc and free in Cn Implicit: application allocates, but does not free spacel E.g. garbage collection in Java, ML or LispAllocationAllocationn In both cases the memory allocator provides an abstraction ofmemory as a set of blocksn Doles out free memory blocks to applicationWill discuss simple explicit memory allocation todayWill discuss simple explicit memory allocation todayApplicationDynamic Memory AllocatorHeap Memory– 4 –15-213, F’02Process Memory ImageProcess 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 heap memoryfrom the operatingsystem using the sbrkfunction.– 5 –15-213, F’02Malloc PackageMalloc Package#include <#include <stdlibstdlib.h>.h>void *void *mallocmalloc(size_t size)(size_t size)n If successful:l Returns a pointer to a memory block of at least size bytes, (typically)aligned to 8-byte boundary.l If size == 0, returns NULLn If unsuccessful: returns NULLvoid free(void *p)void free(void *p)n Returns the block pointed at by p to pool of available memoryn p must come from a previous call to malloc or realloc.void *void *reallocrealloc(void *p, size_t size)(void *p, size_t size)n Changes size of block p and returns pointer to new block.n Contents of new block unchanged up to min of old and new size.– 6 –15-213, F’02Malloc ExampleMalloc 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 */}– 7 –15-213, F’02AssumptionsAssumptionsAssumptions made in this lectureAssumptions made in this lecturen Memory is word addressed (each word can hold a pointer)Allocated block(4 words)Free block(3 words)Free wordAllocated word– 8 –15-213, F’02Allocation ExamplesAllocation Examplesp1 = malloc(4)p2 = malloc(5)p3 = malloc(6)free(p2)p4 = malloc(2)– 9 –15-213, F’02ConstraintsConstraintsApplications:Applications:n Can issue arbitrary sequence of allocation and free requestsn Free requests must correspond to an allocated blockAllocatorsAllocatorsn Can’t control number or size of allocated blocksn Must respond immediately to all allocation requestsli.e., can’t reorder or buffer requestsn Must allocate blocks from free memoryli.e., can only place allocated blocks in free memoryn Must align blocks so they satisfy all alignment requirementsl8 byte alignment for GNU malloc (libc malloc) on Linux boxesn Can only manipulate and modify free memoryn Can’t move the allocated blocks once they are allocatedli.e., compaction is not allowed– 10 –15-213, F’02Goals of Good malloc/freeGoals of Good malloc/freePrimary goalsPrimary goalsn Good time performance for malloc and freel Ideally should take constant time (not always possible)l Should certainly not take linear time in the number of blocksn Good space utilizationl User allocated structures should be large fraction of the heap.l Want to minimize “fragmentation”.Some other goalsSome other goalsn Good locality propertiesl Structures allocated close in time should be close in spacel “Similar” objects should be allocated close in spacen Robustl Can check that free(p1) is on a valid allocated object p1l Can check that memory references are to allocated space– 11 –15-213, F’02Performance Goals: ThroughputPerformance Goals: ThroughputGiven some sequence of Given some sequence of malloc malloc and free requests:and free requests:n R0, R1, ..., Rk, ... , Rn-1Want to maximize throughput and peak memoryWant to maximize throughput and peak memoryutilization.utilization.n These goals are often conflictingThroughput:Throughput:n Number of completed requests per unit timen Example:l 5,000 malloc calls and 5,000 free calls in 10 secondsl Throughput is 1,000 operations/second.– 12 –15-213, F’02Performance Goals:Peak Memory UtilizationPerformance Goals:Peak Memory UtilizationGiven some sequence of Given some sequence of mallocmalloc and free requests: and free requests:n R0, R1, ..., Rk, ... , Rn-1Def: Aggregate payload Def: Aggregate payload PPkk::n malloc(p) results in a block with a payload of p bytes..n After request Rk has completed, the aggregate payload Pk isthe sum of currently allocated payloads.Def: Current heap size is denoted by Def: Current heap size is denoted by HHkkn Assume that Hk is monotonically nondecreasingDef: Peak memory utilization:Def: Peak memory utilization:n After k requests, peak memory utilization is:l Uk = ( maxi<k Pi ) / Hk– 13 –15-213, F’02Internal FragmentationInternal FragmentationPoor memory utilization caused by Poor memory utilization caused by fragmentationfragmentation..n Comes in two forms: internal and external fragmentationInternal fragmentationInternal fragmentationn For some block, internal fragmentation is the difference betweenthe block size and the payload size.n Caused by overhead of maintaining heap data structures, paddingfor alignment purposes, or explicit policy decisions (e.g., not
View Full Document