Heap Memory in C Programming - Stack Overflow

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

The heap is the diametrical opposite of the stack. The heap is a large pool of memory that can be used ... 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 HeapMemoryinCProgramming AskQuestion Asked 10years,3monthsago Modified 4years,6monthsago Viewed 37ktimes 8 5 Whatexactlyisheapmemory? Wheneveracalltomallocismade,memoryisassignedfromsomethingcalledasheap.Whereexactlyisheap.Iknowthataprograminmainmemoryisdividedintoinstructionsegmentwhereprogramstatementsarepresents,Datasegmentwhereglobaldataresidesandstacksegmentwherelocalvariablesandcorrespondingfunctionparametersarestored.Now,whataboutheap? cmemoryheap-memory Share Improvethisquestion Follow editedApr6,2017at21:08 MateuszPiotrowski 7,01499goldbadges4949silverbadges7575bronzebadges askedApr17,2012at23:24 RahulRahul 18911goldbadge22silverbadges1313bronzebadges 0 Addacomment  |  4Answers 4 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 14 Theheapispartofyourprocess'saddressspace.Theheapcanbegrownorshrunk;youmanipulateitbycallingbrk(2)orsbrk(2).Thisisinfactwhatmalloc(3)does. Allocatingfromtheheapismoreconvenientthanallocatingmemoryonthestackbecauseitpersistsafterthecallingroutinereturns;thus,youcancallaroutine,sayfuncA(),toallocateabunchofmemoryandfillitwithsomething;thatmemorywillstillbevalidafterfuncA()returns.IffuncA()allocatesalocalarray(onthestack)thenwhenfuncA()returns,theon-stackarrayisgone. Adrawbackofusingtheheapisthatifyouforgettoreleaseheap-allocatedmemory,youmayexhaustit.Thefailuretoreleaseheap-allocatedmemory(e.g.,failingtofree()memorygottenfrommalloc())issometimescalledamemoryleak. Anothernicefeatureoftheheap,vs.justallocatingalocalarray/struct/whateveronthestack,isthatyougetareturnvaluesayingwhetheryourallocationsucceeded;ifyoutrytoallocatealocalarrayonthestackandyourunout,youdon'tgetanerrorcode;typicallyyourthreadwillsimplybeaborted. Share Improvethisanswer Follow editedApr18,2012at5:22 CharlesMenguy 39.9k1717goldbadges9595silverbadges116116bronzebadges answeredApr17,2012at23:37 collincollin 14133bronzebadges 3 "Allocatingfromtheheapismoreconvenientthanallocatingmemoryonthestackbecauseitpersistsafterthecallingroutinereturn"--thelogichereisincompleteandinvalid;itshouldreadmorelike"Allocatingfromtheheapismoreconvenientthanallocatingonthestackbecause[weusememorythatpersistsafterthecallingroutinereturnand]itpersistsafterthecallingroutinereturn."Nowyoushouldseeonethingthat'swrongwiththat;innotallcasesdoweneedmemorywithsuchpersistence,andcallingfreewhennotneededisnotmoreconvenient,contrarytotheassertion. – autistic Jan20,2018at21:24 Furthermore,evenwhenyoudousememorywhichrequiresalifetimebeyondthatoftheimmediatefunction,youhavetwootheroptions:1/preferably(andthisshouldbeyourgoalmostofthetime)youshouldacceptanargumentpointingtoanobject,andthatobjectcanhaveanystorageduration;thecallerdecideswhethermallocisnecessary(thisishowstrcat,sprintf,etcoperate)and2/therearetwootherstoragedurationswhichyou'venotmentioned(staticandthread-specific),andit'snotspecifiedwhetherthey'reattachedtoaheaporastack(orregisters,fwiw)... – autistic Jan20,2018at21:29 There'sevenoftenathirdoption,whichisup-stream,where-byyouremovethedependencyuponvariadicarraysandfocusonprocessingfixeddatabyte-by-byte(withoutkeepingacopy)asyoureceiveitfromthesource.Infact,youcouldalmostrefertotheregularfilesystemasthoughit'sanotherformofstorageduration,exceptthattheCstandarddoesn'tdefinefilesverystrictly. – autistic Jan20,2018at21:42 Addacomment  |  9 Theheapisthediametricaloppositeofthestack.Theheapisalargepoolofmemorythatcanbeuseddynamically–itisalsoknownasthe“freestore”.Thisismemorythatisnotautomaticallymanaged–youhavetoexplicitlyallocate(usingfunctionssuchasmalloc),anddeallocate(e.g.free)thememory.Failuretofreethememorywhenyouarefinishedwithitwillresultinwhatisknownasamemoryleak–memorythatisstill“beingused”,andnotavailabletootherprocesses.Unlikethestack,therearegenerallynorestrictionsonthesizeoftheheap(orthevariablesitcreates),otherthanthephysicalsizeofmemoryinthemachine.Variablescreatedontheheapareaccessibleanywhereintheprogram. Oh,andheapmemoryrequiresyoutousepointers. Asummaryoftheheap: theheapismanagedbytheprogrammer,theabilitytomodifyitis somewhatboundless inC,variablesareallocatedandfreedusingfunctionslikemalloc()andfree() theheapislarge,andisusuallylimitedbythephysicalmemoryavailable theheaprequirespointerstoaccessit credittocraftofcoding Share Improvethisanswer Follow answeredJan20,2018at20:39 yehudacorsiayehudacorsia 15522silverbadges77bronzebadges 3 Acomprehensiveanswertothequestion;Idohaveafewsuggestions,though.Forastart,youprobablymeanttowrite"Objectscreatedontheheapareaccessibleanywhereintheprogram."ratherthan"Variablescreatedontheheapareaccessibleanywhereintheprogram."Secondly,thoughtheprogrammerperhapsindirectlymanipulatestheheapbycallingmalloc,theabilityfortheprogrammertomodifysuchanunderlyingstructureisnotsomewhatboundless;ifyousteptoofar,youventureintoundefinedbehaviour,whichiswhereyou'vebrokentherulesofC. – autistic Jan20,2018at21:56 BreakingtherulesinCmayappearasthoughyou'vesteppedacrossaboundary.Infact,thatisthecaseforbufferoverflows,forexample.Sometimesyougetanoverflowthatworks...othertimes,youdon't.Breakingrulesdoesn'thavewelldefinedconsequences,andtheboundsformanipulationofthatunderlyingstructurewithoutinvokingUBaresomewhatbound:Youcanaddentriesbycallingmalloc,varyentriesusingreallocandremoveentriesusingfree. – autistic Jan20,2018at21:59 BreakingtherulesinCmayappearasthoughyou'vesteppedacrossaboundary.Infact,thatisthecaseforbufferoverflows,forexample.Sometimesyougetanoverflowthatworks...othertimes,youdon't.Breakingrulesdoesn'thavewelldefinedconsequences,andtheboundsformanipulationofthatunderlyingstructurearesomewhatbound:Youcanaddentriesbycallingmalloc,varyentriesusingreallocandremoveentriesusingfree. – autistic Jan20,2018at21:59 Addacomment  |  3 Basically,aftermemoryisconsumedbytheneedsofprograms,whatisleftistheheap.InCthatwillbethememoryavailableforthecomputer,forvirtualmachinesitwillbelessthanthat. But,thisisthememorythatcanbeusedatrun-timeasyourprogramneedsmemorydynamically. Youmaywanttolookatthisformoreinfo: http://computer.howstuffworks.com/c28.htm Share Improvethisanswer Follow answeredApr17,2012at23:29 JamesBlackJamesBlack 41.2k99goldbadges8585silverbadges163163bronzebadges 5 Who+1dthis?I'mjustcuriousastowhatvaluetodrawfromthis,becauseitseemslikeacompletelyinvalidanswer.Perhapsyoucanclarify...you'resayingthat1/oncesomememoryisinusebyaprogram,it'sintheheap?Orareyousaying2/oncetheprogramisfinishedwiththememory,itgoesintotheheap?Eitherofthesearewrong.Doesthisincluderegistermemoryandmemoryonarotationalharddrive? – autistic Jan20,2018at21:48 Also,thatisanexampleofareallypoorresourceforlearningC.Ifyouneedamanualtoreferto,it'sthePOSIXmallocmanual,whichyou'llnoticemakesnoreferencetothetermheap,asthepeoplewhowroteyourheapunderstand(justaswellasyoushould)thatitisn'tnecessarilyaheap;it'sabook-keepingspace. – autistic Jan20,2018at21:50 @Sebivor-thememorythatisn'tusedbytheapplicationiswhatIwascallingtheheap.Soyouhavealltheallocationsthatispartofstartingupanapplication,andthememorythatisavailableformallocistheheap. – JamesBlack Jan26,2018at3:19 AccordingtotheClanguage,thestoragedurationmadeavailablebymallociscalledallocatedstorageduration;there'snomentionatallofaheapinC.Onx86(duetoassembly),youmaybe(typically)correct...butthat'sassembly,notC;there'snorequirementthataheapbeused;itcouldjustaseasilybeastackorsomeotherkindofgraph.Infact,Ithinkanoptimalimplementationmayheadtowardsagraphofheapsallocatedperthreadwhichhasedgescorrespondingtosynchronisation. – autistic Jan26,2018at4:59 Thisreputablewebsitelistsyourreferenceunderthesectionentitled"Stuffthatshouldbeavoided",forwhatit'sworth.Youshouldbecitingfromthestandard.Goodluckfindingacitationfortheheap! – autistic Jan26,2018at5:00 Addacomment  |  0 Readingthroughthis,thisisactuallybeyondtherealmsofC.Cdoesn'tspecifythatthere'saheapbehindmalloc;itcouldjustaseasilybecalledalinkedlist;you'rejustcallingitaheapbyconvention. Whatthestandardguaranteesisthatmallocwilleitherreturnapointertoanobjectthathasdynamicstorageduration,andyourheapisjustonetypeofdatastructurewhichfacilitatestheprovisionofsuchastorageduration.It'sthecommonchoice.Nonetheless,theverydeveloperswhowroteyourheaphaverecognisedthatitmightnotbeaheap,andsoyou'llseenoreferenceofthetermheapinthePOSIXmallocmanualforexample. OtherthingsthatarebeyondtherealmsofstandardCincludesuchdetailsofthemachinecodebinarywhichisnolongerCsourcecodefollowingcompilation.Thelayoutdetails,thoughtypical,areallimplementation-specificasopposedtoC-specific. Theheap,orwhicheverbook-keepingdatastructureisusedtoaccountforallocations,isgeneratedduringruntime;asmallociscalled,newentriesare(presumably)addedtoitandasfreeiscalled,newentriesare(again,presumably)removedfromit. Asaresult,there'sgenerallynoneedtohaveasectioninthemachinecodebinaryforobjectsallocatedusingmalloc,howevertherearecaseswhereapplicationsareshippedstandalonebakedintomicroprocessors,andinsomeofthesecasesyoumightfindthatflashorotherwisenon-volatilememorymightbereservedforthatuse. Share Improvethisanswer Follow editedJan20,2018at21:52 answeredJan20,2018at21:21 autisticautistic 14.9k22goldbadges3535silverbadges7979bronzebadges 2 Heapspaceissometimesallocatedstatically,thusincludedinthebinary,inembeddedsystems.Basicallypre-allocatedstoragespace,andmalloc/freewouldusethatspaceinsteadofaprocessspaceallocatedbytheunderlyingruntimeenvironment.Haven’thadtodothatforsometime,butusedto. – DaveNewton Jan20,2018at21:25 @DaveNewtonTrue,that.Cometothinkofit,it'susedinJavasmartcards.Mybad!Ta:) – autistic Jan20,2018at21:31 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedcmemoryheap-memoryoraskyourownquestion. TheOverflowBlog Measurableandmeaningfulskilllevelsfordevelopers SanFrancisco?MorelikeSanFrancis-go(Ep.468) FeaturedonMeta AnnouncingtheStacksEditorBetarelease! The[shopping]and[shop]tagsarebeingburninated Linked 8 HeapMemoryandSlaballocation -1 FreeingstringfromanonconstantpointerparameterinC -2 HeapinC++create Related 9060 Whatandwherearethestackandheap? 615 WhatREALLYhappenswhenyoudon'tfreeaftermallocbeforeprogramtermination? 3228 ImproveINSERT-per-secondperformanceofSQLite 3605 HowcanIcreateamemoryleakinJava? 229 Whatdoesthebrk()systemcalldo? 159 Whyisthe.bsssegmentrequired? 227 StackvsheapallocationofstructsinGo,andhowtheyrelatetogarbagecollection 197 WhereinmemoryaremyvariablesstoredinC? HotNetworkQuestions Whyisthereawhitepanelinastronaut’sfabricheadcovertheywearinsidethehardhelmet? HowtoextendusefullifeofIRLEDandphotodiodepair Submittingrevisedmanuscriptlongbeforeduedate Isitnecessarytoprovidecontactinformationfortensofco-authorswhensubmittingapaperfromalargecollaboration? Ethicsofkeepingagiftcardyouwonataraffleataconferenceyourcompanysentyouto? HaveanymilitarypersonnelservingademocraticstatebeenprosecutedaccordingtothefourthNurembergprinciple(superiororder)? Asa(non)residentalienintheUS,whatdocuments(ifany)doesoneneedtocarryatalltimes? Cardinalityofintegerpartsofrealclosedfields Revisedmanuscriptsenttoanewrefereeaftereditorhearingbackfromonereferee:What'sthepossiblereason? DoesaVialofAcid,Oil,AlchemistFire,orotherimprovisedweaponadventuringgearstillrequireanObjectInteractionto'draw'first? DidtheAlgol68standardallowaproceduretobecalledbeforeitsdeclaration? LinkedListimplementationinc++withallfunctions Eggusinggeonodesnotworking WhatisthedifferenceBetweenActiveAcousticsMonitoring(AAM)andPassiveAcousticsMonitoring(PAM)? WhatwasthebugfortheBitcoinvalueoverflowin2010? Animestylemovieaboutmutatedpeoplethatgainmurderousabilitiessuchasprojectile-shootinglimbsandlimbswithbladesontheends Willa10mmeyepiecewithabarlow2xproducethesameresultasa5mmeyepiece? Stumped-partidentification Whywouldspacetraderspickupandoffloadtheirgoodsfromanorbitingplatformratherthandirecttotheplanet? Isthereanameforthisfallacywhensomeonesayssomethingisgoodbyonlypointingoutthegoodthings? Ifaspecieskeepsgrowingthroughouttheir200-300yearlife,what"growthcurve"wouldbemostreasonable/realistic? CouldtheGermangovernmentdecidetofreeRussiancitizenVadimKrasikovfromprison? DidPharaohnotrecogniseMosesafterfortyyears? Teachinga7yoresponsibilityforhischoices morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?