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.
延伸文章資訊
- 1Java筆記:觀念釐清-stack及heap的差異 - iT 邦幫忙
基本型別: byte 、 short 、 int 、 long 、 float 、 double 、 boolean 、 char · 類別型態(或稱參考型態):Class Type ( Ref...
- 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...
- 3[探索5 分鐘] stack 與heap 的底層概念
stack 用於靜態記憶體配置, 大陸翻譯為棧, 棧, 棧(why ?) heap 用於動態記憶體配置, 大陸翻譯為堆. 抱怨一下, 堆跟棧我一直覺得命名混亂, 用Google 翻譯也 ...
- 4stack和heap的區別@ 程式專欄 - 隨意窩
1、棧區(stack)— 由編譯器自動分配釋放,存放函數的參數值,局部變量的值等。其操作方式類似於數據結構中的棧。 2、堆區(heap) — 一般由程序員分配釋放, 若程序員 ...
- 5Java 面試- JVM 的Stack 和Heap - Laugh Now
Stack 和Heap 是JVM 記憶體儲存資料或指令的區域。 · Java 的資料類型分為兩種:Primitive Type 和Class Type。 · Stack 存取速度快,但資料長度及...