CS 225 | Stack and Heap Memory

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

As shown above, the stack segment is near the top of memory with high address. Every time a function is called, the machine allocates some stack memory for it. CS225 Lectures Assignments Exams Resources CourseInfo Honors Noresult BacktoResources Overview Whenaprogramisrunning,ittakesupmemory.Sometimeswearenotevenawareofthememorybeingallocated.Infact,everytimeyoucreateanewvariable,yourprogramisallocatingmorememoryforyoutostorethatvariable.Thisarticlefocusesontwokindsofmemories:stackandheap. GeneralMemoryLayout Eachrunningprogramhasitsownmemorylayout,separatedfromotherprograms.Thelayoutconsistsofalotofsegments,including: stack:storeslocalvariables heap:dynamicmemoryforprogrammertoallocate data:storesglobalvariables,separatedintoinitializedanduninitialized text:storesthecodebeingexecuted Inordertopinpointeachmemorylocationinaprogram’smemory,weassigneachbyteofmemoryan“address”.Theaddressesgofrom0allthewaytothelargestpossibleaddress,dependingonthemachine.Asthefigurebelow,thetext,data,andheapsegmentshavelowaddressnumbers,whilethestackmemoryhashigheraddresses. Memorylayoutofac++program Byconvention,weexpresstheseaddressesinbase16numbers.Forinstance,thesmallestpossibleaddressis0x00000000(wherethe0xmeansbase16),andthelargestpossibleaddresscouldbe0xFFFFFFFF. Stack Asshownabove,thestacksegmentisnearthetopofmemorywithhighaddress.Everytimeafunctioniscalled,themachineallocatessomestackmemoryforit.Whenanewlocalvariablesisdeclared,morestackmemoryisallocatedforthatfunctiontostorethevariable.Suchallocationsmakethestackgrowdownwards.Afterthefunctionreturns,thestackmemoryofthisfunctionisdeallocated,whichmeansalllocalvariablesbecomeinvalid.Theallocationanddeallocationforstackmemoryisautomaticallydone.Thevariablesallocatedonthestackarecalledstackvariables,orautomaticvariables. Thefollowingfiguresshowexamplesofwhatstackmemorylookslikewhenthecorrespondingcodeisrun: 1.Allocatevariableaformain 2.Allocatebformainandstore-3 3.Allocatecformainandstore12345 4.Allocatepformainandstoreaddressofb 5.Allocatevariableaforhelloandstore100 6.Deallocatethestackmemoryofhelloandreturn100tomain 7.Allocatedformainandstore100 8.Deallocatethestackmemoryofmainandreturn0 Previous Next Sincethestackmemoryofafunctiongetsdeallocatedafterthefunctionreturns,thereisnoguaranteethatthevaluestoredinthoseareawillstaythesame.Acommonmistakeistoreturnapointertoastackvariableinahelperfunction.Afterthecallergetsthispointer,theinvalidstackmemorycanbeoverwrittenatanytime.Thefollowingfiguresdemonstrateoneexampleofsuchscenario.AssumethereisaCubeclassthathasmethodsgetVolumeandgetSurfaceArea,aswellasaprivatevariablewidth. 1.AllocateCubecforCreateCube 2.DeallocatestackmemoryofCreateCubeandreturnaddressofc 3.Allocatepointercformainandstorethereturnedvalue.NoticethatthestackmemoryofCreateCubeisoverwritten 4.AllocatestackmemoryforgetVolumeandcalculatevolumeusingthewidthofc.Sincethewidthofciscorrupted,thevolumeisalsoincorrect 5.DeallocatememoryofgetVolume.AllocaterformaintostorethereturnvalueofgetVolume 6.AllocatestackmemoryforgetSurfaceAreaandcalculatesurfaceareausingthewidthofc.SimilartogetVolume,thesurfaceareacalculatedwillbeincorrect 7.DeallocatememoryofgetSurfaceArea.AllocatevformaintostorethereturnvalueofgetSurfaceArea 8.Deallocatethestackmemoryofmainandreturn0 Previous Next Theseexamplesprovideasimplifiedversionofstackmemory.Inreality,afunction’sstackstoresmorethanjustlocalvariables.Youcanfindoutmoreaboutwhatexactlyisinthestackbytakingacomputerarchitectureclass.Inaddition,theaboveexamplecouldcauseasegmentationfaultwhenwearecallingc->getVolume()orc->getSurfaceArea().Thisisbecauseifthevalueofcisinvalid,thenthemachinecan’tfindthegetVolumefunctionassociatedwithc.Ifthishappens,thisprogramwillcrashinsteadofproducingincorrectvalues. Heap Intheprevioussectionwesawthatfunctionscannotreturnpointersofstackvariables.Tosolvethisissue,youcaneitherreturnbycopy,orputthevalueatsomewheremorepermanentthanstackmemory.Heapmemoryissuchaplace.Unlikestackmemory,heapmemoryisallocatedexplicitlybyprogrammersanditwon’tbedeallocateduntilitisexplicitlyfreed.ToallocateheapmemoryinC++,usethekeywordnewfollowedbytheconstructorofwhatyouwanttoallocate.Thereturnvalueofnewoperatorwillbetheaddressofwhatyoujustcreated(whichpointstosomewhereintheheap). Thefiguresbelowdemonstratewhathappensinbothstackandheapwhenthecorrespondingcodeisexecuted: 1.Allocateanintegerwithdefaultvalue0ontheheap,allocateponmain'sstacktostoretheaddressoftheinteger 2.AllocateaCubewithdefaultwidth20ontheheap,allocatec1onmain'sstacktostoretheaddressoftheCube 3.Allocatec2onmain'sstackandstoreacopyofc1 4.CallmethodsetLengthonc2,changesthewidthoftheCubepointedbybothc1andc2 5.Deallocatestackmemoryofmainandreturn0 Previous Next Youmaynoticeintheaboveexamplethatevenattheendoftheprogram,theheapmemoryisstillnotfreed.Thisiscalledamemoryleak. Memoryleaksinsmallprogramsmightnotlooklikeabigdeal,butforlong-runningservers,memoryleakscanslowdownthewholemachineandeventuallycausetheprogramtocrash. Tofreeheapmemory,usethekeyworddeletefollowedbythepointertotheheapmemory.Becarefulaboutthememoryyoufreed.Ifyoutrytousethepointerstothosememoryafteryoufreethem,itwillcauseundefinedbehavior.Toavoidsuchissues,itisgoodpracticetosetthevalueoffreedpointerstonullptrimmediatelyafterdelete.Hereisanexamplethatcorrectlyfreesmemoryafterusingit. 1.AllocateaCubewidth20ontheheap,allocateaCubepointerconCreateCubeOnHeap'sstacktostoretheaddressoftheCube 2.DeallocatestackmemoryforCreateCubeOnHeapandreturnthevalueofpointerc 3.Allocatecubeonmain'sstackandstorethereturnedpointer 4.CallmethodgetVolumeoncube,whichcalculatesthevolumetobe8000 5.Allocatedoublevtostorethereturnvalue8000 6.DeallocatetheCubepointedbycube,noticethatcubeisstillpointingtoinvalidmemoryonheap 7.Setthevalueofcubetonullptr,whichis0 8.Deallocatethestackmemoryofmain Previous Next Inthefiguresabove,youcanseethatheapmemoryarenotallocatedcontinuouslyfrombottomtotop.Thisisbecauseunlikestackwheretheinvalidmemoryisalwaysatthebottom,theusercanfreeheapmemorythat’sinbetweenvalidmemories,causingfragmentationsintheheap.Inordertoreusememoryefficiently,therearenumerousheapallocationschemethattrytopickthe“best”spotforyou.Youwilllearnmoreaboutmemoryallocationinasystemprogrammingclass.



請為這篇文章評分?