7. Memory : Stack vs Heap - Paul Gribble

文章推薦指數: 80 %
投票人數:10人

To allocate memory on the heap, you must use malloc() or calloc() , which are built-in C functions. Once you have allocated memory on the heap, ... UP | HOME 7.Memory:StackvsHeap TableofContents StackvsHeap TheStack TheHeap StackvsHeapProsandCons Stack Heap Examples WhentousetheHeap? Links StackvsHeap Sofarwehaveseenhowtodeclarebasictypevariablessuchasint, double,etc,andcomplextypessuchasarraysandstructs.Theway wehavebeendeclaringthemsofar,withasyntaxthatislikeother languagessuchasMATLAB,Python,etc,putsthesevariableson thestackinC. TheStack Whatisthestack?It'saspecialregionofyourcomputer'smemory thatstorestemporaryvariablescreatedbyeachfunction(including themain()function).Thestackisa"LIFO"(lastin,firstout) datastructure,thatismanagedandoptimizedbytheCPUquite closely.Everytimeafunctiondeclaresanewvariable,itis"pushed" ontothestack.Theneverytimeafunctionexits,allofthe variablespushedontothestackbythatfunction,arefreed(thatis tosay,theyaredeleted).Onceastackvariableisfreed,thatregion ofmemorybecomesavailableforotherstackvariables. Theadvantageofusingthestacktostorevariables,isthatmemoryis managedforyou.Youdon'thavetoallocatememorybyhand,orfreeit onceyoudon'tneeditanymore.What'smore,becausetheCPU organizesstackmemorysoefficiently,readingfromandwritingto stackvariablesisveryfast. Akeytounderstandingthestackisthenotionthatwhenafunction exits,allofitsvariablesarepoppedoffofthestack(andhence lostforever).Thusstackvariablesarelocalinnature.Thisis relatedtoaconceptwesawearlierknownasvariablescope,or localvsglobalvariables.AcommonbuginCprogrammingisattempting toaccessavariablethatwascreatedonthestackinsidesome function,fromaplaceinyourprogramoutsideofthatfunction (i.e.afterthatfunctionhasexited). Anotherfeatureofthestacktokeepinmind,isthatthereisalimit (varieswithOS)onthesizeofvariablesthatcanbestoredonthe stack.Thisisnotthecaseforvariablesallocatedontheheap. Tosummarizethestack: thestackgrowsandshrinksasfunctionspushandpoplocalvariables thereisnoneedtomanagethememoryyourself,variablesareallocatedandfreedautomatically thestackhassizelimits stackvariablesonlyexistwhilethefunctionthatcreatedthem,isrunning TheHeap Theheapisaregionofyourcomputer'smemorythatisnotmanaged automaticallyforyou,andisnotastightlymanagedbytheCPU.Itis amorefree-floatingregionofmemory(andislarger).Toallocate memoryontheheap,youmustusemalloc()orcalloc(),whichare built-inCfunctions.Onceyouhaveallocatedmemoryontheheap,you areresponsibleforusingfree()todeallocatethatmemoryonceyou don'tneeditanymore.Ifyoufailtodothis,yourprogramwillhave whatisknownasamemoryleak.Thatis,memoryontheheapwill stillbesetaside(andwon'tbeavailabletootherprocesses).Aswe willseeinthedebuggingsection,thereisatoolcalledvalgrind thatcanhelpyoudetectmemoryleaks. Unlikethestack,theheapdoesnothavesizerestrictionsonvariable size(apartfromtheobviousphysicallimitationsofyour computer).Heapmemoryisslightlyslowertobereadfromandwritten to,becauseonehastousepointerstoaccessmemoryontheheap.We willtalkaboutpointersshortly. Unlikethestack,variablescreatedontheheapareaccessiblebyany function,anywhereinyourprogram.Heapvariablesareessentially globalinscope. StackvsHeapProsandCons Stack veryfastaccess don'thavetoexplicitlyde-allocatevariables spaceismanagedefficientlybyCPU,memorywillnotbecomefragmented localvariablesonly limitonstacksize(OS-dependent) variablescannotberesized Heap variablescanbeaccessedglobally nolimitonmemorysize (relatively)sloweraccess noguaranteedefficientuseofspace,memorymaybecomefragmentedovertimeasblocksofmemoryareallocated,thenfreed youmustmanagememory(you'reinchargeofallocatingandfreeingvariables) variablescanberesizedusingrealloc() Examples Hereisashortprogramthatcreatesitsvariablesonthestack.It looksliketheotherprogramswehaveseensofar. #include doublemultiplyByTwo(doubleinput){ doubletwice=input*2.0; returntwice; } intmain(intargc,char*argv[]) { intage=30; doublesalary=12345.67; doublemyList[3]={1.2,2.3,3.4}; printf("doubleyoursalaryis%.3f\n",multiplyByTwo(salary)); return0; } doubleyoursalaryis24691.340 Onlines10,11and12wedeclarevariables:anint,adouble,and anarrayofthreedoubles.Thesethreevariablesarepushedontothe stackassoonasthemain()functionallocatesthem.Whenthe main()functionexits(andtheprogramstops)thesevariablesare poppedoffofthestack.Similarly,inthefunctionmultiplyByTwo(), thetwicevariable,whichisadouble,ispushedontothestackas soonasthemultiplyByTwo()functionallocatesit.Assoonasthe multiplyByTwo()functionexits,thetwicevariableispoppedoff ofthestack,andisgoneforever. Asasidenote,thereisawaytotellCtokeepastackvariable around,evenafteritscreatorfunctionexits,andthatistousethe statickeywordwhendeclaringthevariable.Avariabledeclaredwith thestatickeywordthusbecomessomethinglikeaglobalvariable, butonethatisonlyvisibleinsidethefunctionthatcreatedit.It's astrangeconstruction,onethatyouprobablywon'tneedexceptunder veryspecificcircumstances. Hereisanotherversionofthisprogramthatallocatesallofitsvariablesontheheapinsteadofthestack: #include #include double*multiplyByTwo(double*input){ double*twice=malloc(sizeof(double)); *twice=*input*2.0; returntwice; } intmain(intargc,char*argv[]) { int*age=malloc(sizeof(int)); *age=30; double*salary=malloc(sizeof(double)); *salary=12345.67; double*myList=malloc(3*sizeof(double)); myList[0]=1.2; myList[1]=2.3; myList[2]=3.4; double*twiceSalary=multiplyByTwo(salary); printf("doubleyoursalaryis%.3f\n",*twiceSalary); free(age); free(salary); free(myList); free(twiceSalary); return0; } Asyoucansee,usingmalloc()toallocatememoryontheheapand thenusingfree()todeallocateit,isnobigdeal,butisabit cumbersome.Theotherthingtonoticeisthatthereareabunchof starsymbols*allovertheplacenow.Whatarethose?Theanswer is,theyarepointers.Themalloc()(andcalloc()andfree()) functionsdealwithpointersnotactualvalues.Wewilltalkmore aboutpointersshortly.Thebottomlinethough:pointersareaspecial datatypeinCthatstoreaddressesinmemoryinsteadofstoring actualvalues.Thusonline5above,thetwicevariableisnota double,butisapointertoadouble.It'sanaddressinmemory wherethedoubleisstored. WhentousetheHeap? Whenshouldyouusetheheap,andwhenshouldyouusethestack?If youneedtoallocatealargeblockofmemory(e.g.alargearray,ora bigstruct),andyouneedtokeepthatvariablearoundalongtime (likeaglobal),thenyoushouldallocateitontheheap.Ifyouare dealingwithrelativelysmallvariablesthatonlyneedtopersistas longasthefunctionusingthemisalive,thenyoushouldusethe stack,it'seasierandfaster.Ifyouneedvariableslikearraysand structsthatcanchangesizedynamically(e.g.arraysthatcangrowor shrinkasneeded)thenyouwilllikelyneedtoallocatethemonthe heap,andusedynamicmemoryallocationfunctionslikemalloc(), calloc(),realloc()andfree()tomanagethatmemory"by hand".Wewilltalkaboutdynamicallyallocateddatastructuresafter wetalkaboutpointers. Links TheStackandtheHeap WhatandWherearethestackandheap PaulGribble|Summer2012ThisworkislicensedunderaCreativeCommonsAttribution4.0InternationalLicense



請為這篇文章評分?