1MemoryAllocationCS217MemoryAllocation• Goodprogrammersmakeefficientuseofmemory• UnderstandingmemoryallocationisimportantCreatedatastructuresofarbitrarysizeAvoid“memoryleaks”Run-timeperformanceMemory• Whatismemory?Storageforvariables,data,code,etc.CPUMemoryDiskNetworkVideoAudioDataBus2Memory• Whatismemory?Storageforvariables,data,code,etc.Unixprovidesvirtualmemory00xffffffffVirtualAddressSpaceCPUMemoryDiskNetworkVideoAudioDataBus3232MemoryLayout• Howismemoryorganized?Text=codeData=constantsBSS=globalandstaticvariablesStack=localvariablesHeap=dynamicmemory00xffffffffTextDataBSSStackHeapMemoryLayoutintiSize;char*f(void){char*p;iSize=8;p=malloc(iSize);returnp;}bssstackdataheap00xffffffffTextDataBSSStackHeap3MemoryAllocation• Howismemoryallocated?Globalandstaticvariables=programstartupLocalvariables=functioncallDynamicmemory= malloc()00xffffffffTextDataBSSStackHeapMemoryAllocationallocatedinBSS,settozeroatstartupallocatedonstackatstartoffunctionf8bytesallocatedinheapby mallocintiSize;char*f(void){char*p;iSize=8;p=malloc(iSize);returnp;}MemoryDeallocation• Howismemorydeallocated?Globalandstaticvariables=programfinishLocalvariables=functionreturnDynamicmemory=free()• AllmemoryisdeallocatedatprogramterminationItisgoodstyletofreeallocatedmemoryanyway4MemoryDeallocationavailableuntilprogramterminationdeallocated byreturnfromfunctionfdeallocate bycallingfree(p)intiSize;char*f(void){char*p;iSize=8;p=malloc(iSize);returnp;}DynamicMemory#include<stdlib.h>void*malloc(size_tsize);voidfree(void*ptr);00xffffffffTextDataBSSStack}HeapHeapchar*p1=malloc(3);char*p2=malloc(1);char*p3= malloc(4);free(p2);char*p4= malloc(6);free(p3);char*p5= malloc(2);free(p1);free(p4);free(p5);StaticLocalVariables•static keywordindeclarationoflocalvariablemeans:Available(ifwithinscope)throughoutentireprogramexecutionVariableisallocatedfromBSS,notstackActslikeglobalvariablewithlimitedscopeintiSize;char*f(void){static int first=1;if(first){iSize =GetSize();first=0;}...}00xffffffffTextDataBSSStackHeap5MemoryInitialization• Localvariableshaveundefinedvaluesint count;• Memoryallocatedby malloc hasundefinedvalueschar*p=malloc(8);• Ifyouneedavariabletostartwithaparticularvalue,useanexplicitinitializerint count=0;p[0]=’\0’;• Globalandstaticvariablesareinitializedto0bydefaultstatic int count=0;isthesameasstaticint count;ItisbadstyletodependonthisExampleProgram00xffffffffTextDataBSSStackHeap#include<stdio.h>#include<string.h>#defineMAX_STRINGS128#defineMAX_STRING_LENGTH256void ReadStrings(char**strings, int *nstrings, intmaxstrings,FILE*fp){charstring[MAX_STRING_LENGTH];*nstrings =0;while(fgets(string,MAX_STRING_LENGTH, fp)){strings[(*nstrings)++]= strdup(string);if(*nstrings >= maxstrings)break;}}...int main(){char*strings[MAX_STRINGS];intnstrings;ReadStrings(strings,&nstrings,MAX_STRINGS, stdin);SortStrings(strings, nstrings);WriteStrings(strings, nstrings, stdout);return0;}Summary• ThreetypesofmemoryGlobalandstaticvariables=BSSLocalvariables=stackDynamicmemory=heap• Threetypesofallocation/deallocation strategiesGlobalandstaticvariables(BSS)=programstartup/terminationLocalvariables(stack)=functionentry/returnDynamicmemory(heap)=malloc()/free()•
View Full Document