What and where are the stack and heap?

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

The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Whatandwherearethestackandheap? AskQuestion Asked 13years,9monthsago Modified 19daysago Viewed 1.8mtimes 9018 5219 Programminglanguagebooksexplainthatvaluetypesarecreatedonthestack,andreferencetypesarecreatedontheheap,withoutexplainingwhatthesetwothingsare.Ihaven'treadaclearexplanationofthis.Iunderstandwhatastackis.But, Whereandwhatarethey(physicallyinarealcomputer'smemory)? TowhatextentaretheycontrolledbytheOSorlanguagerun-time? Whatistheirscope? Whatdeterminesthesizeofeachofthem? Whatmakesonefaster? memory-managementstacklanguage-agnosticdynamic-memory-allocationheap-memory Share Improvethisquestion Follow editedJun13,2021at11:54 trincot 267k3030goldbadges219219silverbadges254254bronzebadges askedSep17,2008at4:18 mattshanemattshane 90.2k33goldbadges1616silverbadges55bronzebadges 7 231 areallygoodexplanationcanbefoundhereWhat’sthedifferencebetweenastackandaheap? – Songo Dec16,2013at11:32 17 Also(really)good:codeproject.com/Articles/76153/…(thestack/heappart) – Ben Feb15,2014at5:50 18 youtube.com/watch?v=clOUdVDDzIM&spfreload=5 – Selvamani Jun11,2016at5:42 4 Related,seeStackClash.TheStackClashremediationsaffectedsomeaspectsofsystemvariablesandbehaviorslikerlimit_stack.AlsoseeRedHatIssue1463241 – jww Jun21,2017at16:23 4 @mattshaneThedefinitionsofstackandheapdon'tdependonvalueandreferencetypeswhatsoever.Inotherwords,thestackandheapcanbefullydefinedevenifvalueandreferencetypesneverexisted.Further,whenunderstandingvalueandreferencetypes,thestackisjustanimplementationdetail.PerEricLippert:TheStackIsAnImplementationDetail,PartOne. – Matthew Nov12,2017at22:38  |  Show2morecomments 30Answers 30 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 6578 Thestackisthememorysetasideasscratchspaceforathreadofexecution.Whenafunctioniscalled,ablockisreservedonthetopofthestackforlocalvariablesandsomebookkeepingdata.Whenthatfunctionreturns,theblockbecomesunusedandcanbeusedthenexttimeafunctioniscalled.ThestackisalwaysreservedinaLIFO(lastinfirstout)order;themostrecentlyreservedblockisalwaysthenextblocktobefreed.Thismakesitreallysimpletokeeptrackofthestack;freeingablockfromthestackisnothingmorethanadjustingonepointer. Theheapismemorysetasidefordynamicallocation.Unlikethestack,there'snoenforcedpatterntotheallocationanddeallocationofblocksfromtheheap;youcanallocateablockatanytimeandfreeitatanytime.Thismakesitmuchmorecomplextokeeptrackofwhichpartsoftheheapareallocatedorfreeatanygiventime;therearemanycustomheapallocatorsavailabletotuneheapperformancefordifferentusagepatterns. Eachthreadgetsastack,whilethere'stypicallyonlyoneheapfortheapplication(althoughitisn'tuncommontohavemultipleheapsfordifferenttypesofallocation). Toansweryourquestionsdirectly: TowhatextentaretheycontrolledbytheOSorlanguageruntime? TheOSallocatesthestackforeachsystem-levelthreadwhenthethreadiscreated.TypicallytheOSiscalledbythelanguageruntimetoallocatetheheapfortheapplication. Whatistheirscope? Thestackisattachedtoathread,sowhenthethreadexitsthestackisreclaimed.Theheapistypicallyallocatedatapplicationstartupbytheruntime,andisreclaimedwhentheapplication(technicallyprocess)exits. Whatdeterminesthesizeofeachofthem? Thesizeofthestackissetwhenathreadiscreated.Thesizeoftheheapissetonapplicationstartup,butcangrowasspaceisneeded(theallocatorrequestsmorememoryfromtheoperatingsystem). Whatmakesonefaster? Thestackisfasterbecausetheaccesspatternmakesittrivialtoallocateanddeallocatememoryfromit(apointer/integerissimplyincrementedordecremented),whiletheheaphasmuchmorecomplexbookkeepinginvolvedinanallocationordeallocation.Also,eachbyteinthestacktendstobereusedveryfrequentlywhichmeansittendstobemappedtotheprocessor'scache,makingitveryfast.Anotherperformancehitfortheheapisthattheheap,beingmostlyaglobalresource,typicallyhastobemulti-threadingsafe,i.e.eachallocationanddeallocationneedstobe-typically-synchronizedwith"all"otherheapaccessesintheprogram. Acleardemonstration: Imagesource:vikashazrati.wordpress.com Share Improvethisanswer Follow editedNov28,2021at14:10 user1666620 4,7001717silverbadges2727bronzebadges answeredSep17,2008at4:52 JeffHillJeffHill 68.2k33goldbadges1616silverbadges77bronzebadges 13 129 Goodanswer-butIthinkyoushouldaddthatwhilethestackisallocatedbytheOSwhentheprocessstarts(assumingtheexistenceofanOS),itismaintainedinlinebytheprogram.Thisisanotherreasonthestackisfaster,aswell-pushandpopoperationsaretypicallyonemachineinstruction,andmodernmachinescandoatleast3oftheminonecycle,whereasallocatingorfreeingheapinvolvescallingintoOScode. – sqykly Oct8,2013at8:31 435 I'mreallyconfusedbythediagramattheend.IthoughtIgotituntilIsawthatimage. – SinaMadani Aug15,2016at19:06 12 @Anarelletheprocessorrunsinstructionswithorwithoutanos.AnexampleclosetomyheartistheSNES,whichhadnoAPIcalls,noOSasweknowittoday-butithadastack.Allocatingonastackisadditionandsubtractiononthesesystemsandthatisfineforvariablesdestroyedwhentheyarepoppedbyreturningfromthefunctionthatcreatedthem,butconstrastthatto,say,aconstructor,ofwhichtheresultcan'tjustbethrownaway.Forthatweneedtheheap,whichisnottiedtocallandreturn.MostOShaveAPIsaheap,noreasontodoitonyourown – sqykly Oct13,2016at15:06 6 "stackisthememorysetasideasscratchspace".Cool.Butwhereisitactually"setaside"intermsofJavamemorystructure??IsitHeapmemory/Non-heapmemory/Other(Javamemorystructureasperbetsol.com/2017/06/…) – Jatin Jul22,2018at6:22 6 @JatinShashooJavaruntime,asbytecodeinterpreter,addsonemorelevelofvirtualization,sowhatyoureferredtoisjustJavaapplicationpointofview.Fromoperatingsystempointofviewallthatisjustaheap,whereJavaruntimeprocessallocatessomeofitsspaceas"non-heap"memoryforprocessedbytecode.RestofthatOS-levelheapisusedasapplication-levelheap,whereobject'sdataarestored. – kbec Sep6,2018at15:41  |  Show8morecomments 2589 Stack: StoredincomputerRAMjustliketheheap. Variablescreatedonthestackwillgooutofscopeandareautomaticallydeallocated. Muchfastertoallocateincomparisontovariablesontheheap. Implementedwithanactualstackdatastructure. Storeslocaldata,returnaddresses,usedforparameterpassing. Canhaveastackoverflowwhentoomuchofthestackisused(mostlyfrominfiniteortoodeeprecursion,verylargeallocations). Datacreatedonthestackcanbeusedwithoutpointers. Youwouldusethestackifyouknowexactlyhowmuchdatayouneedtoallocatebeforecompiletimeanditisnottoobig. Usuallyhasamaximumsizealreadydeterminedwhenyourprogramstarts. Heap: StoredincomputerRAMjustlikethestack. InC++,variablesontheheapmustbedestroyedmanuallyandneverfalloutofscope.Thedataisfreedwithdelete,delete[],orfree. Slowertoallocateincomparisontovariablesonthestack. Usedondemandtoallocateablockofdataforusebytheprogram. Canhavefragmentationwhentherearealotofallocationsanddeallocations. InC++orC,datacreatedontheheapwillbepointedtobypointersandallocatedwithnewormallocrespectively. Canhaveallocationfailuresiftoobigofabufferisrequestedtobeallocated. Youwouldusetheheapifyoudon'tknowexactlyhowmuchdatayouwillneedatruntimeorifyouneedtoallocatealotofdata. Responsibleformemoryleaks. Example: intfoo() { char*pBuffer;//



請為這篇文章評分?