CS 225 | Stack and Heap Memory
文章推薦指數: 80 %
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.
延伸文章資訊
- 1[探索5 分鐘] stack 與heap 的底層概念
stack 用於靜態記憶體配置, 大陸翻譯為棧, 棧, 棧(why ?) heap 用於動態記憶體配置, 大陸翻譯為堆. 抱怨一下, 堆跟棧我一直覺得命名混亂, 用Google 翻譯也 ...
- 2CS 225 | Stack and Heap Memory
As shown above, the stack segment is near the top of memory with high address. Every time a funct...
- 3Stack 與Heap 有何差別. 程式設計相關的行業 - Medium
簡單說, Stack 是拿來給程式呼叫function 時存放function 資料用的,而Heap 是用來存放並且管理,程式全部所需要用到的變數與資料。 參考資訊. https:// ...
- 4Java筆記:觀念釐清-stack及heap的差異 - iT 邦幫忙
基本型別: byte 、 short 、 int 、 long 、 float 、 double 、 boolean 、 char · 類別型態(或稱參考型態):Class Type ( Ref...
- 5記憶體- stack 與heap - iT 邦幫忙::一起幫忙解決難題
記憶體- stack 與heap ... stack 的中文叫堆疊,一般是指後進先出的資料結構,不過程式中也有個stack ,是由系統提供給程式暫存區域變數等等用的, ...