Stack vs Heap Memory Allocation - GeeksforGeeks
文章推薦指數: 80 %
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
延伸文章資訊
- 1memory allocation in Stack and Heap
- 2Stack vs Heap Memory Allocation - GeeksforGeeks
- 3C 語言程式的記憶體配置概念教學 - GT Wang
這個區段通常位於heap 或stack 之後,避免因heap 或stack 溢位而覆寫CPU ... heap 區段的記憶體空間用於儲存動態配置的變數,例如C 語言的 malloc ...
- 4Stack / Heap 區分-出自於藍森林(備份)
heap:是由malloc之類函數分配的空間所在地。地址是由低向高增長的。 stack:是自動分配變量,以及函數調用的時候所使用的一些空間。
- 5Pointers, Stack & Heap Memory, malloc( )
The malloc( ) (memory allocate) function can be used to dynamically allocate an area of memory to...