memory allocation in Stack and Heap

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

Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2). When allocating blocks of memory larger than ... 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 memoryallocationinStackandHeap AskQuestion Asked 10years,11monthsago Modified 1year,6monthsago Viewed 64ktimes 27 16 Thismayseemlikeaverybasicquestion,butitsbeeninmyheadso: Whenweallocatealocalvariable,itgoesintostack.Similarlydynamicallocationcausethevariabletogoonheap.Now,myquestionis,isthisvariableactuallylieonstackorheaporwewilljustareferenceinthestackandHeap. Forexample, SupposeIdeclareavariableinti.Nowthisiisallocatedonthestack.So,whenIprinttheaddressofi,thiswillbeoneofthelocationonstack?Samequestionforheapaswell. cmemory-managementheap-memorydynamic-allocationstack-memory Share Improvethisquestion Follow editedAug8,2016at22:18 gsamaras 69.9k4040goldbadges173173silverbadges279279bronzebadges askedJul21,2011at2:09 SamirBaidSamirBaid 1,02822goldbadges1111silverbadges1818bronzebadges 1 Idon'tquiteunderstandyourquestion.ButyoucanreadthebookComputerSystems-AProgrammer'sPerspectiveandyouwillknowtheanswer. – Stan Jul21,2011at2:22 Addacomment  |  6Answers 6 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 78 I'mnotentirelysurewhatyou'reasking,butI'lltrymybesttoanswer. Thefollowingdeclaresavariableionthestack: inti; WhenIaskforanaddressusing&iIgettheactuallocationonthestack. WhenIallocatesomethingdynamicallyusingmalloc,thereareactuallyTWOpiecesofdatabeingstored.Thedynamicmemoryisallocatedontheheap,andthepointeritselfisallocatedonthestack.Sointhiscode: int*j=malloc(sizeof(int)); Thisisallocatingspaceontheheapforaninteger.It'salsoallocatingspaceonthestackforapointer(j).Thevariablej'svalueissettotheaddressreturnedbymalloc. Share Improvethisanswer Follow editedAug8,2016at22:18 gsamaras 69.9k4040goldbadges173173silverbadges279279bronzebadges answeredJul21,2011at2:16 ChrisEberleChrisEberle 46.9k1212goldbadges8080silverbadges118118bronzebadges 7 ThanksChrisforyouranswer.Thiswastheansweriwaslookingfor.So,thatisthereasonwhywehaveaproblemofProgramsrunningoutofStackbutneveroutofHEAP,becauseHEAPwouldbelimitedbythememorysystemhas. – SamirBaid Jul21,2011at2:20 2 Actuallytheonlyreasonthatprogramsrunoutofstackspacesoquicklyisbecauseit'scommonpracticetoputverysmalllimitsonthestackspace(Ithink8KBisprettycommon).Andyes,theheapcangetprettydangbigifyouletit. – ChrisEberle Jul21,2011at2:22 1 @Samirno.Bothstackandheaparelimitedbytheamountofsystemmemory.Programsrunoutofstackbeforetheyrunoutofheapbecausethestacksizesistypicallyordersofmagnitudesmallerthantheheap.Programscanstillrunoutofheapthough. – MattBall Jul21,2011at2:23 1 @Chris:OnWindows,thelimitisusually1MB,not8kB.Iassumethatothersystemshavesimilarlimits.Ofcourse,thisisprobablyverydifferentforembeddedsystems. – RudyVelthuis Jul21,2011at2:28 1 @Rudy:IthoughtthatonWindowsthelimitswerecompiledINTOthebinary,andthereforeuptothedeveloper.Icoulddefinitelybelievethat1MBisthedefault,8KBseemsprettyspartanifyouaskme... – ChrisEberle Jul21,2011at2:31  |  Show2morecomments 15 Hopefullythefollowingishelpful: voidfoo() { //anintegerstoredonthestack inta_stack_integer; //apointertointegerdata,thepointeritselfisstoredonthestack int*a_stack_pointer; //makea_stack_pointer"point"tointegerdatathat'sallocatedontheheap a_stack_pointer=(int*)malloc(10*sizeof(int)); } Inthecaseofstackvariables,thevariableitself(theactualdata)isstoredonthestack. Inthecaseofheapallocatedmemory,theunderlyingdataisalwaysstoredontheheap.Apointertothismemory/datamaybestoredlocallyonthestack. Hopethishelps. Share Improvethisanswer Follow answeredJul21,2011at2:19 DarrenEngwirdaDarrenEngwirda 6,78044goldbadges2323silverbadges4242bronzebadges 2 ThiswashelpfulDarren,butcanyouexplaintomeascearniowheretheincaseofheapallocatedmemory,pointermaynotbestoredonstack? – SamirBaid Jul21,2011at2:24 @Samir:Youmayhaveamorecomplexdatastructure,wheretheheapallocateddatacontainspointerstoothersegmentsofheapallocateddata.Theconventionalimplementationofalinked-listwouldbeanexampleofthis,whereeach"node"inthelistcontainsapointertothenext"node"andsoon – DarrenEngwirda Jul21,2011at2:27 Addacomment  |  6 Thepointervariableitselfwouldresideonthestack.Thememorythatthepointerpointstowouldresideontheheap. int*i=malloc(sizeof(int)); iwouldresideonthestack,theactualmemorythatipointsto*iwouldbeontheheap. Share Improvethisanswer Follow answeredJul21,2011at2:17 SurootSuroot 4,22911goldbadge2121silverbadges2828bronzebadges Addacomment  |  2 IagreewithChris.Justanotherwaytoexplainthat.Considerthefollowingcode: int*j=malloc(sizeof(int)); free(j); Evenafterusingfree(j)whichshoulddeallocatethememoryfromtheheap,thepointerstillexistsandweneedtoexplicitlymakeitNULL.Thisdefinitelysuggeststhatthereisalsoastackcounterpartofthepointerotherwiseitshouldhavebeeninexistentafterthefreecommand.Thisstackvariableistheonepointingtotheaddressontheheapwherethememorywasdynamicallyallocatedusingmalloc. Share Improvethisanswer Follow answeredJun3,2013at10:08 PrateekPrateek 66511goldbadge77silverbadges77bronzebadges Addacomment  |  1 Mr.Eberle'sansweris100%correct,butsinceGoogleshowsthisasthefirstanswerwhensearchingformallocheaporstack,Ihavetoaddthatmalloc()allocatesdataontheheap'most'ofthetime.IftheallocateddatawaslargerthanMMAP_THRESHOLDwhichisusually128kbon32-bitsystems,malloc()willnotusetheheapandinsteadallocatesthedatainanAnonymousMemorySegmentlocatedusuallybelowthestack,growinginthedirectionoflowmemory. Thisisthesameregionthatdynamicallyloadedlibrariesarelocated(libc.so,etc.).Here'stherelevantpassagefrommanmalloc: Normally,malloc()allocatesmemoryfromtheheap,andadjuststhe sizeoftheheapasrequired,usingsbrk(2).Whenallocatingblocks ofmemorylargerthanMMAP_THRESHOLDbytes,the glibcmalloc()implementationallocatesthememoryasaprivateanonymousmappingusingmmap(2).MMAP_THRESHOLDis128kBbydefault, butisadjustableusingmallopt(3).Priorto Linux4.7allocationsperformedusingmmap(2)wereunaffectedbytheRLIMIT_DATAresourcelimit;sinceLinux4.7,thislimitisalso enforcedforallocationsperformedusingmmap(2). Asapracticalexample,feelfreetocheckthefollowingpost.Itbasicallyallocates300kbwithmalloc()andthenrunspmaptoshowtherelevantmemorysegment. Share Improvethisanswer Follow answeredAug25,2018at9:23 solidaksolidak 4,94533goldbadges2727silverbadges3333bronzebadges 1 PrettysureMMAP_THRESHOLDisn'tpartofANSI/ISOCoranyPOSIXstandard.Stillinteresting,butnotaninherenttruthofallCimplementations.Lookslikethat'strueforglibcandmuslthough. – WyattWard Nov22,2019at6:59 Addacomment  |  0 stackorheaparenotseparatememory,theyarememorysegmentsthatarunningprogramisallocatedbythesystem,justdifferentwaysoforganizingdatainmemory. Sowhenyouget&i,itisamemoryaddress,simpleasthat. Share Improvethisanswer Follow answeredJul21,2011at2:19 AnhPhamAnhPham 5,42133goldbadges2121silverbadges2727bronzebadges 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?Browseotherquestionstaggedcmemory-managementheap-memorydynamic-allocationstack-memoryoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool AskWizardTestResultsandNextSteps Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Trending:Anewanswersortingoption Linked 2 AssigningvaluestoCpointersusingmallocwithoutvariableinitialization 2 malloc:Anonymousmappingandmagicarea 1 Segmentationfaultwhentwomatricessizeareover800*800 -1 Carrayofstructsinmalloc 0 Problemwithpushingelementstothestackinc 1 Differencebetweenusingmallocandchararray[i]whenusingstrorageinfunctions Related 2855 Whatisthedifferencebetween#includeand#include"filename"? 2971 Howdoyouset,clear,andtoggleasinglebit? 9018 Whatandwherearethestackandheap? 534 Whichisfaster:StackallocationorHeapallocation 614 WhatREALLYhappenswhenyoudon'tfreeaftermallocbeforeprogramtermination? 88 Memoryallocation:StackvsHeap? 40 Classmembersandexplicitstack/heapallocation 223 StackvsheapallocationofstructsinGo,andhowtheyrelatetogarbagecollection HotNetworkQuestions Whatisthenameofthecategoryforthevibrationsthatthetonguedoesinlinguistics? Isthereageneralwaytoparametrize2-qubitunitaries? nonrecursivequicksortinc++ Formallanguagerewriterules:strangenotation WhydidoldconsoleshavespecialRAMdedicatedforaspecifictask? SciFiinvolvingportalstodistantworldsthatleavepeoplestrandedfarfromearth Iboughtmyfirstroadbike,andithurtsmybackandhands HowdoIsetvaluenodeto#frameusingpython Whydoesthegovernmentnotintroduceanamendmenttotheconstitutiontoallowabortion? TheUnaverageables Children'sscifibookfrom'90s/early2000sthathadacoverwithtwokids,andaringedplanetinthebackground SolvingaSimple'SumandProduct'Problem What'smakingthescenariocontradictorytoMaxwell'stheoryofemwaves? WhatarethecorrectspecsforanSNESpowersupply? HowcanIremovemarkerswithnumbers2,5,7? HowtomakeQuantityrememberinterpretation? Whydoprogunandantiabortion(andviceversa)viewsgotogetherintheUSA? HowcanIaddalayerofmeaningtoanevilcampaign? Whatisthemeaningof"payinginbuttons"? Whydidn’tthe1980smicrosuseMC68010? Whatisthebestsolutiontoshowtheinvisibleareaofawindowwhenit'stoobig? WhatisthepurposeofthefuelpumpsintheA320? WhatcanIdoifaflightdelaymakesmemissthetransferfromtheairport? Howareanygunrestrictionsconstitutional? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?