Stack vs Heap Memory Allocation - GeeksforGeeks

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

Memory in a C/C++/Java program can either be allocated on a stack or a heap. Prerequisite: Memory layout of C program. Stack Allocation: The ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesStackvsHeapMemoryAllocationMemoryLayoutofCProgramsWhatarethedefaultvaluesofstaticvariablesinC?Understanding“volatile”qualifierinC|Set2(Examples)ConstQualifierinCInitializationofstaticvariablesinCUnderstanding“register”keywordinCUnderstanding“extern”keywordinCStorageClassesinCStaticVariablesinCHowtodeallocatememorywithoutusingfree()inC?DifferenceBetweenmalloc()andcalloc()withExamplesDynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()Howtodynamicallyallocatea2DarrayinC?Howtopassa2DarrayasaparameterinC?MultidimensionalArraysinC/C++2DVectorInC++WithUserDefinedSizeVectorofVectorsinC++STLwithExamplesVectorinC++STLTheC++StandardTemplateLibrary(STL)SortinC++StandardTemplateLibrary(STL)DifferencebetweenBFSandDFSClassmethodvsStaticmethodinPythonDifferencebetweencomparingStringusing==and.equals()methodinJavaDifferencesbetweenTCPandUDPDifferencesbetweenBlackBoxTestingvsWhiteBoxTestingDifferencesbetweenJDK,JREandJVMDifferencesbetweenProceduralandObjectOrientedProgrammingDifferencebetweenIntelandAMDStackvsHeapMemoryAllocationMemoryLayoutofCProgramsWhatarethedefaultvaluesofstaticvariablesinC?Understanding“volatile”qualifierinC|Set2(Examples)ConstQualifierinCInitializationofstaticvariablesinCUnderstanding“register”keywordinCUnderstanding“extern”keywordinCStorageClassesinCStaticVariablesinCHowtodeallocatememorywithoutusingfree()inC?DifferenceBetweenmalloc()andcalloc()withExamplesDynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()Howtodynamicallyallocatea2DarrayinC?Howtopassa2DarrayasaparameterinC?MultidimensionalArraysinC/C++2DVectorInC++WithUserDefinedSizeVectorofVectorsinC++STLwithExamplesVectorinC++STLTheC++StandardTemplateLibrary(STL)SortinC++StandardTemplateLibrary(STL)DifferencebetweenBFSandDFSClassmethodvsStaticmethodinPythonDifferencebetweencomparingStringusing==and.equals()methodinJavaDifferencesbetweenTCPandUDPDifferencesbetweenBlackBoxTestingvsWhiteBoxTestingDifferencesbetweenJDK,JREandJVMDifferencesbetweenProceduralandObjectOrientedProgrammingDifferencebetweenIntelandAMDStackvsHeapMemoryAllocationViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 13Jun,2022MemoryinaC/C++/Javaprogramcaneitherbeallocatedonastackoraheap.Prerequisite:MemorylayoutofCprogram.StackAllocation:Theallocationhappensoncontiguousblocksofmemory.Wecallitastackmemoryallocationbecausetheallocationhappensinthefunctioncallstack.Thesizeofmemorytobeallocatedisknowntothecompilerandwheneverafunctioniscalled,itsvariablesgetmemoryallocatedonthestack.Andwheneverthefunctioncallisover,thememoryforthevariablesisde-allocated.Thisallhappensusingsomepredefinedroutinesinthecompiler.Aprogrammerdoesnothavetoworryaboutmemoryallocationandde-allocationofstackvariables.ThiskindofmemoryallocationalsoknownasTemporarymemoryallocationbecauseassoonasthemethodfinishesitsexecutionallthedatabelongstothatmethodflushesoutfromthestackautomatically.Means,anyvaluestoredinthestackmemoryschemeisaccessibleaslongasthemethodhasn’tcompleteditsexecutionandcurrentlyinrunningstate.KeyPoints:It’satemporarymemoryallocationschemewherethedatamembersareaccessibleonlyifthemethod()thatcontainedthemiscurrentlyisrunning.Itallocatesorde-allocatesthememoryautomaticallyassoonasthecorrespondingmethodcompletesitsexecution.WereceivethecorrespondingerrorJava.lang.StackOverFlowErrorbyJVM,Ifthestackmemoryisfilledcompletely.Stackmemoryallocationisconsideredsaferascomparedtoheapmemoryallocationbecausethedatastoredcanonlybeaccessbyownerthread.Memoryallocationandde-allocationisfasterascomparedtoHeap-memoryallocation.Stack-memoryhaslessstoragespaceascomparedtoHeap-memory.CPPintmain(){   //Allthesevariablesgetmemory   //allocatedonstack   inta;   intb[10];   intn=20;   intc[n];}HeapAllocation:Thememoryisallocatedduringtheexecutionofinstructionswrittenbyprogrammers.Notethatthenameheaphasnothingtodowiththeheapdatastructure.Itiscalledheapbecauseitisapileofmemoryspaceavailabletoprogrammerstoallocatedandde-allocate.EverytimewhenwemadeanobjectitalwayscreatesinHeap-spaceandthereferencinginformationtotheseobjectsarealwaysstoredinStack-memory.Heapmemoryallocationisn’tassafeasStackmemoryallocationwasbecausethedatastoredinthisspaceisaccessibleorvisibletoallthreads.Ifaprogrammerdoesnothandlethismemorywell,amemoryleakcanhappenintheprogram.TheHeap-memoryallocationisfurtherdividedintothreecategories:-Thesethreecategorieshelpustoprioritizethedata(Objects)tobestoredintheHeap-memoryorintheGarbagecollection.YoungGeneration–It’stheportionofthememorywhereallthenewdata(objects)aremadetoallocatethespaceandwheneverthismemoryiscompletelyfilledthentherestofthedataisstoredinGarbagecollection.OldorTenuredGeneration–ThisisthepartofHeap-memorythatcontainstheolderdataobjectsthatarenotinfrequentuseornotinuseatallareplaced.PermanentGeneration–ThisistheportionofHeap-memorythatcontainstheJVM’smetadatafortheruntimeclassesandapplicationmethods.KeyPoints:WereceivethecorrespondingerrormessageifHeap-spaceisentirelyfull, java.lang.OutOfMemoryErrorbyJVM.ThismemoryallocationschemeisdifferentfromtheStack-spaceallocation,herenoautomaticde-allocationfeatureisprovided.WeneedtouseaGarbagecollectortoremovetheoldunusedobjectsinordertousethememoryefficiently.Theprocessingtime(Accessingtime)ofthismemoryisquiteslowascomparedtoStack-memory.Heap-memoryisalsonotthreaded-safeasStack-memorybecausedatastoredinHeap-memoryarevisibletoallthreads.SizeofHeap-memoryisquitelargerascomparedtotheStack-memory.Heap-memoryisaccessibleorexistsaslongasthewholeapplication(orjavaprogram)runs.CPPintmain(){   //Thismemoryfor10integers   //isallocatedonheap.   int*ptr =newint[10];}IntermixedexampleofbothkindofmemoryallocationHeapandStackinjava:JavaclassEmp{    intid;    Stringemp_name;     publicEmp(intid,Stringemp_name){        this.id=id;        this.emp_name=emp_name;    }} publicclassEmp_detail{    privatestaticEmpEmp_detail(intid,Stringemp_name){        returnnewEmp(id,emp_name);    }     publicstaticvoidmain(String[]args){        intid=21;        Stringname="Maddy";        Empperson_=null;        person_=Emp_detail(id,emp_name);    }}Followingaretheconclusionsonwhichwe’llmakeafteranalyzingtheaboveexample:Aswestartexecutionofthehaveprogram,alltherun-timeclassesarestoredintheHeap-memoryspace.Thenwefindthemain()methodinthenextlinewhichisstoredintothestackalongwithallit’sprimitive(orlocal)andthereferencevariableEmpoftypeEmp_detailwillalsobestoredintheStackandwillpointouttothecorrespondingobjectstoredinHeapmemory.ThenthenextlinewillcalltotheparameterizedconstructorEmp(int,String)frommain()andit’llalsoallocatetothetopofthesamestackmemoryblock.Thiswillstore:Theobjectreferenceoftheinvokedobjectofthestackmemory.Theprimitivevalue(primitivedatatype)intidinthestackmemory.ThereferencevariableofStringemp_nameargumentwhichwillpointtotheactualstringfromstringpoolintotheheapmemory.ThenthemainmethodwillagaincalltotheEmp_detail()staticmethod,forwhichallocationwillbemadeinstackmemoryblockontopofthepreviousmemoryblock.So,forthenewlycreatedobjectEmpoftypeEmp_detailandallinstancevariableswillbestoredinheapmemory.PictorialrepresentationasshownintheFigure.1below:Fig.1KeyDifferencesBetweenStackandHeapAllocations  Inastack,theallocationandde-allocationareautomaticallydonebythecompilerwhereasinheap,itneedstobedonebytheprogrammermanually.HandlingofHeapframeiscostlierthanthehandlingofthestackframe.Memoryshortageproblemismorelikelytohappeninstackwhereasthemainissueinheapmemoryisfragmentation.Stackframeaccessiseasierthantheheapframeasthestackhaveasmallregionofmemoryandiscache-friendly,butincaseofheapframeswhicharedispersedthroughoutthememorysoitcausesmorecachemisses.Astackisnotflexible,thememorysizeallottedcannotbechangedwhereasaheapisflexible,andtheallottedmemorycanbealtered.Accessingtimeofheaptakesismorethanastack.ComparisonChartParameterSTACKHEAPBasicMemoryisallocatedinacontiguousblock.Memoryisallocatedinanyrandomorder.AllocationandDe-allocationAutomaticbycompilerinstructions.Manualbytheprogrammer.CostLessMoreImplementationEasyHardAccesstimeFasterSlowerMainIssueShortageofmemoryMemoryfragmentationLocalityofreferenceExcellentAdequateSafetyThreadsafe,datastoredcanonlybeaccessedbyownerNotThreadsafe,datastoredvisibletoallthreadsFlexibilityFixed-sizeResizingispossibleDatatypestructureLinearHierarchicalPreferredStaticmemoryallocationispreferredinarray.Heapmemoryallocationispreferredinthelinkedlist.SizeSmallthanheapmemory.Largerthanstackmemory.MyPersonalNotes arrow_drop_upSave LikeNext MemoryLayoutofCProgramsRecommendedArticlesPage:31,Mar2031,Mar2002,Nov2018,Aug2021,Apr2006,Nov2025,Feb1814,Jun1912,Dec1813,May1921,May1927,May1922,Sep1722,Feb2104,Jul2110,Jul2112,Sep1125,Jul1623,Apr1709,Apr1812,Jan1818,Apr1811,May1824,Mar20ArticleContributedBy:Ankit_Bisht@Ankit_BishtVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:ShubhamKattaashushrma378madhav_mohanSagarPawarshubhamsharma8337nehasagar144dev6251priyansh70890ArticleTags:system-programmingTechnicalScripter2018DifferenceBetweenTechnicalScripterReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinDifferenceBetweenDifferencebetweenvar,letandconstkeywordsinJavaScriptDifferencesbetweenIPv4andIPv6DifferenceBetweenMethodOverloadingandMethodOverridinginJavaDifferencebetweenClusteredandNon-clusteredindexDifferencebetweenProcessandThreadMorerelatedarticlesinDifferenceBetweenmapvsunordered_mapinC++DifferencebetweenInternalandExternalfragmentationDifferencesandApplicationsofList,Tuple,SetandDictionaryinPythonDifferencebetweenSQLandNoSQLPython|DifferenceBetweenListandTupleImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?