memory allocation in Stack and Heap
文章推薦指數: 80 %
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()andthenrunspmap
延伸文章資訊
- 1Virtual Memory - Heap and Stack Memory - Course Websites
- 2Stack vs Heap Memory Allocation - GeeksforGeeks
- 3Dynamic Memory Allocation via malloc or the stack
malloc is the standard C way to allocate memory from "the heap", the area of memory where most of...
- 4memory allocation in Stack and Heap
Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, ...
- 5memory allocation in Stack and Heap