Dynamic Memory Allocation IApr 1, 2003Topics Simple explicit allocatorsz Data structuresz Mechanismsz Policiesclass20.ppt15-213“The course that gives CMU its Zip!”–2–15-213, F’03Harsh RealityMemory MattersMemory is not unbounded It must be allocated and managed Many applications are memory dominatedz 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 program performance Adapting program to characteristics of memory system can lead to major speed improvements–3–15-213, F’03Dynamic Memory AllocationExplicit vs. Implicit Memory Allocator Explicit: application allocates and frees space z E.g., malloc and free in C Implicit: application allocates, but does not free spacez E.g. garbage collection in Java, ML or LispAllocation In both cases the memory allocator provides an abstraction of memory as a set of blocks Doles out free memory blocks to applicationWill discuss simple explicit memory allocation todayApplicationDynamic Memory AllocatorHeap Memory–4–15-213, F’03Process Memory Imagekernel virtual memoryMemory mapped region forshared librariesrun-time heap (via malloc)program text (.text)initialized data (.data)uninitialized data (.bss)stack0%espmemory invisibleto user codethe “brk” ptrAllocators requestadditional heap memoryfrom the operating system using the sbrkfunction.–5–15-213, F’03Malloc Package#include <stdlib.h>void *malloc(size_t size) If successful:z Returns a pointer to a memory block of at least size bytes, (typically) aligned to 8-byte boundary.z If size == 0, returns NULL If unsuccessful: returns NULL (0) and sets errno.void 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 pointer to new block. Contents of new block unchanged up to min of old and new size.–6–15-213, F’03Malloc Examplevoid foo(int n, int m) {int i, *p;/* allocate a block of n ints */p = (int *)malloc(n * sizeof(int));if (p == 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’03AssumptionsAssumptions made in this lecture 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’03Allocation Examplesp1 = malloc(4)p2 = malloc(5)p3 = malloc(6)free(p2)p4 = malloc(2)–9–15-213, F’03ConstraintsApplications: 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 requestszi.e., can’t reorder or buffer requests Must allocate blocks from free memoryzi.e., can only place allocated blocks in free memory Must align blocks so they satisfy all alignment requirementsz8 byte alignment for GNU malloc (libc malloc) on Linux boxes Can only manipulate and modify free memory Can’t move the allocated blocks once they are allocatedzi.e., compaction is not allowed–10–15-213, F’03Goals of Good malloc/freePrimary goals Good time performance for malloc and freez Ideally should take constant time (not always possible)z Should certainly not take linear time in the number of blocks Good space utilizationz User allocated structures should be large fraction of the heap.z Want to minimize “fragmentation”.Some other goals Good locality propertiesz Structures allocated close in time should be close in spacez “Similar” objects should be allocated close in space Robustz Can check that free(p1) is on a valid allocated object p1z Can check that memory references are to allocated space–11–15-213, F’03Performance Goals: ThroughputGiven some sequence of malloc and free requests: R0, R1, ..., Rk, ... , Rn-1Want to maximize throughput and peak memory utilization. These goals are often conflictingThroughput: Number of completed requests per unit time Example:z 5,000 malloc calls and 5,000 free calls in 10 seconds z Throughput is 1,000 operations/second.–12–15-213, F’03Performance 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 Rkhas completed, the aggregate payload Pkisthe sum of currently allocated payloads.Def: Current heap size is denoted by Hk Assume that Hkis monotonically nondecreasingDef: Peak memory utilization: After k requests, peak memory utilization is:z Uk= ( maxi<kPi) / Hk–13–15-213, F’03Internal FragmentationPoor memory utilization caused by fragmentation. Comes in two forms: internal and external fragmentationInternal fragmentation For some block, internal fragmentation is the difference betweenthe block size and the payload size. Caused by overhead of maintaining heap data structures, padding for alignment purposes, or explicit policy decisions (e.g., not tosplit the block). Depends only on the pattern of previous requests, and thus is easy to measure.payloadInternalfragmentationblockInternalfragmentation–14–15-213, F’03External 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. –15–15-213, F’03Implementation Issuesz How do we know how much memory to free just given a pointer?z How do we keep track of the free blocks?z What do we do with the extra space when allocating a structure that is smaller than the free block it is placed in?z How do we pick a block to use for allocation -- manymight fit?z How do we reinsert freed block?p1 = malloc(1)p0free(p0)–16–15-213, F’03Knowing How Much to FreeStandard method Keep the length of a block in the word preceding the block.zThis word is often
View Full Document