Dynamic Memory Allocation via malloc or the stack

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

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=rspisalreadyinuse:likeapreservedregister,you'renotallowedtochangethismemory. Ifyoudo,theprogramislikelytocrash,probablywhenyoutrytoreturn. Anymemoryaddress



請為這篇文章評分?