Dynamic Memory Allocation via malloc or the stack
文章推薦指數: 80 %
malloc is the standard C way to allocate memory from "the heap", the area of memory where most of a program's stuff is stored. Unlike the C++ "new" operator ...
DynamicMemoryAllocationviamalloc,andthestack
sizeof(dog_in_window)
Anytimeyou'redoinglowlevelmemorymanipulation,youneedtokeepinmindhowmanybytesareusedbyanobject. Forexample,toallocatememory,youneedthesizeinbytes. Todopointermanipulation,likeskippingoveranobjecttofindthenextobject,youneedthesizeinbytestoknowhowfartoskip.
Arraytype
Firstelement
Movetonext
Access i'thelement
Arrayofchar(string)
BYTE[ ptr ]
ptr+1
BYTE[ ptr + i ]
Arrayofinteger
DWORD[ ptr ]
ptr+4
DWORD[ ptr +4*i ]
Arrayoflongs
QWORD[ ptr ]
ptr+8
QWORD[ ptr +8*i ]
There'sahandykeyword"sizeof"builtintoCandC++,thatyoucanapplytoanyvariableortypename,tofindouthowmanybytesofstorageitrequires. Forexample,ifyouwanttoknowifyou'rerunningona64-bitmachine,where"long"is64bitsor8bytes,youjustprintthesize:
returnsizeof(long);
(TrythisinNetRunnow!)
Thisreturns8onmymachines,indicating"long"takes8bytes.
Thisprovidesaninterestingwaytoseeinsideobjects,bymeasuringtheirsize. Forexample,thissecretiveclassisstilljust8bytes,indicatinginmemoryit'sjustone"long"integer. Youcaneventypecastaclasspointertoalongintpointer,dereferencethepointer,andthere'sthevalue. Norealmystery!
classarcane_mystery{
private:longdark_secrets;
};
returnsizeof(arcane_mystery);
(TrythisinNetRunnow!)
Thereisn'tanyequivalentto"sizeof"inassemblylanguage--youjustneedtorememberthesizesofeverythingyourself!
Dynamicallocationwithmalloc
mallocisthestandardCwaytoallocatememoryfrom"theheap",theareaofmemorywheremostofaprogram'sstuffisstored. UnliketheC++"new"operator,mallocdoesn'texplicitlyknowwhichdatatypeit'sallocating,sinceitsonlyparameteristhenumberofbytestoallocate.Thismeansyouneedanuglypointertypecastontheweirdbarepointerreturnvaluefrommalloc.
PlainC, alsoworksinC++
C++
int*arr=(int*)malloc(100*sizeof(int));
int*arr=newint[100];
myClass*c=(myClass*)malloc(sizeof(myClass));
myClass*c=newmyClass;
Tofreememory,callthefunctionfree,like"free(ptr);". Asusual,you'llgetahorriblecrash,sometimesdelayedandsometimesinstant,ifyoufreethesameblockmorethanonce,freememorythatdidn'tcomefrommalloc,freememoryandthensomebodykeepsusingit,ormanyothermisdeeds. Ifyouforgettocallfree,youwon'tgetanimmediatecrash,butinalong-runningprogramlikeanetworkserver,theseun-freedobjectswillbuildupandeventuallyconsumealltheserver'smemory,causingittoslowdownandeventuallycrash.
intlen=3;
int*arr=(int*)malloc(len*sizeof(int));
inti;
for(i=0;i
延伸文章資訊
- 1C 語言程式的記憶體配置概念教學 - GT Wang
這個區段通常位於heap 或stack 之後,避免因heap 或stack 溢位而覆寫CPU ... heap 區段的記憶體空間用於儲存動態配置的變數,例如C 語言的 malloc ...
- 2Stack vs Heap Memory Allocation - GeeksforGeeks
Memory in a C/C++/Java program can either be allocated on a stack or a heap. Prerequisite: Memory...
- 3Objective-C 的基本困難C 語言的記憶體管理malloc - iT 邦幫忙
關於這個主題並不會講解,詳閱Stack based memory allocation - wiki 與Memory management: Heap - wiki。 值得注意的是,Stack ...
- 4Pointers, Stack & Heap Memory, malloc( )
The malloc( ) (memory allocate) function can be used to dynamically allocate an area of memory to...
- 5Heap vs. Stack: Code Examples, Tutorials & More - Stackify