7. Memory : Stack vs Heap - Paul Gribble
文章推薦指數: 80 %
To allocate memory on the heap, you must use malloc() or calloc() , which are built-in C functions. Once you have allocated memory on the heap, ...
UP
|
HOME
7.Memory:StackvsHeap
TableofContents
StackvsHeap
TheStack
TheHeap
StackvsHeapProsandCons
Stack
Heap
Examples
WhentousetheHeap?
Links
StackvsHeap
Sofarwehaveseenhowtodeclarebasictypevariablessuchasint,
double,etc,andcomplextypessuchasarraysandstructs.Theway
wehavebeendeclaringthemsofar,withasyntaxthatislikeother
languagessuchasMATLAB,Python,etc,putsthesevariableson
thestackinC.
TheStack
Whatisthestack?It'saspecialregionofyourcomputer'smemory
thatstorestemporaryvariablescreatedbyeachfunction(including
themain()function).Thestackisa"LIFO"(lastin,firstout)
datastructure,thatismanagedandoptimizedbytheCPUquite
closely.Everytimeafunctiondeclaresanewvariable,itis"pushed"
ontothestack.Theneverytimeafunctionexits,allofthe
variablespushedontothestackbythatfunction,arefreed(thatis
tosay,theyaredeleted).Onceastackvariableisfreed,thatregion
ofmemorybecomesavailableforotherstackvariables.
Theadvantageofusingthestacktostorevariables,isthatmemoryis
managedforyou.Youdon'thavetoallocatememorybyhand,orfreeit
onceyoudon'tneeditanymore.What'smore,becausetheCPU
organizesstackmemorysoefficiently,readingfromandwritingto
stackvariablesisveryfast.
Akeytounderstandingthestackisthenotionthatwhenafunction
exits,allofitsvariablesarepoppedoffofthestack(andhence
lostforever).Thusstackvariablesarelocalinnature.Thisis
relatedtoaconceptwesawearlierknownasvariablescope,or
localvsglobalvariables.AcommonbuginCprogrammingisattempting
toaccessavariablethatwascreatedonthestackinsidesome
function,fromaplaceinyourprogramoutsideofthatfunction
(i.e.afterthatfunctionhasexited).
Anotherfeatureofthestacktokeepinmind,isthatthereisalimit
(varieswithOS)onthesizeofvariablesthatcanbestoredonthe
stack.Thisisnotthecaseforvariablesallocatedontheheap.
Tosummarizethestack:
thestackgrowsandshrinksasfunctionspushandpoplocalvariables
thereisnoneedtomanagethememoryyourself,variablesareallocatedandfreedautomatically
thestackhassizelimits
stackvariablesonlyexistwhilethefunctionthatcreatedthem,isrunning
TheHeap
Theheapisaregionofyourcomputer'smemorythatisnotmanaged
automaticallyforyou,andisnotastightlymanagedbytheCPU.Itis
amorefree-floatingregionofmemory(andislarger).Toallocate
memoryontheheap,youmustusemalloc()orcalloc(),whichare
built-inCfunctions.Onceyouhaveallocatedmemoryontheheap,you
areresponsibleforusingfree()todeallocatethatmemoryonceyou
don'tneeditanymore.Ifyoufailtodothis,yourprogramwillhave
whatisknownasamemoryleak.Thatis,memoryontheheapwill
stillbesetaside(andwon'tbeavailabletootherprocesses).Aswe
willseeinthedebuggingsection,thereisatoolcalledvalgrind
thatcanhelpyoudetectmemoryleaks.
Unlikethestack,theheapdoesnothavesizerestrictionsonvariable
size(apartfromtheobviousphysicallimitationsofyour
computer).Heapmemoryisslightlyslowertobereadfromandwritten
to,becauseonehastousepointerstoaccessmemoryontheheap.We
willtalkaboutpointersshortly.
Unlikethestack,variablescreatedontheheapareaccessiblebyany
function,anywhereinyourprogram.Heapvariablesareessentially
globalinscope.
StackvsHeapProsandCons
Stack
veryfastaccess
don'thavetoexplicitlyde-allocatevariables
spaceismanagedefficientlybyCPU,memorywillnotbecomefragmented
localvariablesonly
limitonstacksize(OS-dependent)
variablescannotberesized
Heap
variablescanbeaccessedglobally
nolimitonmemorysize
(relatively)sloweraccess
noguaranteedefficientuseofspace,memorymaybecomefragmentedovertimeasblocksofmemoryareallocated,thenfreed
youmustmanagememory(you'reinchargeofallocatingandfreeingvariables)
variablescanberesizedusingrealloc()
Examples
Hereisashortprogramthatcreatesitsvariablesonthestack.It
looksliketheotherprogramswehaveseensofar.
#include
延伸文章資訊
- 1Dynamic 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...
- 2Stack / Heap 區分-出自於藍森林(備份)
heap:是由malloc之類函數分配的空間所在地。地址是由低向高增長的。 stack:是自動分配變量,以及函數調用的時候所使用的一些空間。
- 3Objective-C 的基本困難C 語言的記憶體管理malloc - iT 邦幫忙
關於這個主題並不會講解,詳閱Stack based memory allocation - wiki 與Memory management: Heap - wiki。 值得注意的是,Stack ...
- 4C dynamic memory allocation - Wikipedia
Hoard malloc
- 5Stack vs Heap. What's the difference and why should I care?
I'm four months into the self study and I've solved multiple problems using the malloc, realloc, ...