Writing You Own malloc() March 29, 2003Process Memory ImageMalloc PackageAllocation ExamplesGoals of Good malloc/freePerformance Goals: ThroughputPerformance Goals: Peak Memory UtilizationInternal FragmentationExternal FragmentationImplementation IssuesKnowing How Much to FreeKeeping Track of Free BlocksMethod 1: Implicit ListImplicit List: Finding a Free BlockBitfieldsImplicit List: Allocating in Free BlockImplicit List: Freeing a BlockImplicit List: CoalescingImplicit List: Bidirectional CoalescingConstant Time CoalescingConstant Time Coalescing (Case 1)Constant Time Coalescing (Case 2)Constant Time Coalescing (Case 3)Constant Time Coalescing (Case 4)Summary of Key Allocator PoliciesImplicit Lists: SummaryExplicit Free ListsAllocating From Explicit Free ListsFreeing With Explicit Free ListsFreeing With a LIFO Policy (Case 1)Freeing With a LIFO Policy (Case 2)Freeing With a LIFO Policy (Case 3)Freeing With a LIFO Policy (Case 4)Explicit List SummarySlide 35Segregated StorageSimple Segregated StorageSegregated FitsFor More Info on AllocatorsWriting You Own malloc()March 29, 2003Writing You Own malloc()March 29, 2003TopicsExplicit AllocationData structuresMechanismsPoliciesclass19.ppt15-213“The course that gives CMU its Zip!”Adapted From Fall 2003 Lectures– 2 –15-213, F’03Process 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 invisibleto user codethe “brk” ptrAllocators requestadditional heap memoryfrom the operating system using the sbrk function.– 3 –15-213, F’03Malloc PackageMalloc Package#include <stdlib.h>void *malloc(size_t size)If successful:Returns a pointer to a memory block of at least size bytes, (typically) aligned to 8-byte boundary.If size == 0, returns NULLIf unsuccessful: returns NULL (0) and sets errno.void free(void *p)Returns the block pointed at by p to pool of available memoryp 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.– 4 –15-213, F’03Allocation ExamplesAllocation Examplesp1 = malloc(4)p2 = malloc(5)p3 = malloc(6)free(p2)p4 = malloc(2)– 5 –15-213, F’03Goals of Good malloc/free Goals of Good malloc/free Primary goalsGood time performance for malloc and freeIdeally should take constant time (not always possible)Should certainly not take linear time in the number of blocksGood space utilizationUser allocated structures should be large fraction of the heap.Want to minimize “fragmentation”.Some other goalsGood locality propertiesStructures allocated close in time should be close in space“Similar” objects should be allocated close in spaceRobustCan check that free(p1) is on a valid allocated object p1Can check that memory references are to allocated space– 6 –15-213, F’03Performance Goals: ThroughputPerformance 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 timeExample:5,000 malloc calls and 5,000 free calls in 10 seconds Throughput is 1,000 operations/second.– 7 –15-213, F’03Performance Goals: Peak Memory UtilizationPerformance 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 of currently allocated payloads.Def: Current heap size is denoted by HkAssume that Hk is monotonically nondecreasingDef: Peak memory utilization: After k requests, peak memory utilization is:Uk = ( maxi<k Pi ) / Hk– 8 –15-213, F’03Internal FragmentationInternal FragmentationPoor memory utilization caused by fragmentation.Comes in two forms: internal and external fragmentationInternal fragmentationFor some block, internal fragmentation is the difference between the 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 to split the block).Depends only on the pattern of previous requests, and thus is easy to measure.payloadInternal fragmentationblockInternal fragmentation– 9 –15-213, F’03External FragmentationExternal 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.– 10 –15-213, F’03Implementation IssuesImplementation IssuesHow do we know how much memory to free just given a pointer?How do we keep track of the free blocks?What do we do with the extra space when allocating a structure that is smaller than the free block it is placed in?How do we pick a block to use for allocation -- many might fit?How do we reinsert freed block?p1 = malloc(1)p0free(p0)– 11 –15-213, F’03Knowing How Much to FreeKnowing How Much to FreeStandard methodKeep the length of a block in the word preceding the block.This word is often called the header field or headerRequires an extra word for every allocated blockfree(p0)p0 = malloc(4) p0Block size data5– 12 –15-213, F’03Keeping Track of Free BlocksKeeping Track of Free BlocksMethod 1: Implicit list using lengths -- links all blocksMethod 2: Explicit list among the free blocks using pointers within the free blocksMethod 3: Segregated free listDifferent free lists for different size classesMethod 4: Blocks sorted by sizeCan use a balanced tree (e.g. Red-Black tree) with pointers within each free block, and the length used as a key5 4 265 4 26– 13 –15-213, F’03Method 1: Implicit ListMethod 1: Implicit ListNeed to identify whether each block is free or allocatedCan use extra bitBit can be put in the same word as the size if block sizes are always multiples of two (mask out low order bit when reading size).size1 wordFormat ofallocated andfree blockspayloada = 1: allocated block a = 0: free blocksize: block
View Full Document