Creating an array ; This computes the number of bytes that ten integers occupy in memory, then requests that many bytes from malloc and assigns the result to a ...
Cdynamicmemoryallocation
FromWikipedia,thefreeencyclopedia
Jumptonavigation
Jumptosearch
DynamicmemorymanagementintheCprogramminglanguage
Cstandardlibrary(libc)
Generaltopics
Datatypes
Characterclassification
Strings
Mathematics
Fileinput/output
Date/time
Localization
Memoryallocation
Processcontrol
Signals
Alternativetokens
Miscellaneousheaders
vte
CdynamicmemoryallocationreferstoperformingmanualmemorymanagementfordynamicmemoryallocationintheCprogramminglanguageviaagroupoffunctionsintheCstandardlibrary,namelymalloc,realloc,callocandfree.[1][2][3]
TheC++programminglanguageincludesthesefunctions;however,theoperatorsnewanddeleteprovidesimilarfunctionalityandarerecommendedbythatlanguage'sauthors.[4]Still,thereareseveralsituationsinwhichusingnew/deleteisnotapplicable,suchasgarbagecollectioncodeorperformance-sensitivecode,andacombinationofmallocandplacement newmayberequiredinsteadofthehigher-levelnewoperator.
Manydifferentimplementationsoftheactualmemoryallocationmechanism,usedbymalloc,areavailable.Theirperformancevariesinbothexecutiontimeandrequiredmemory.
Contents
1Rationale
2Overviewoffunctions
2.1Differencesbetweenmalloc()andcalloc()
3Usageexample
4Typesafety
4.1Advantagestocasting
4.2Disadvantagestocasting
5Commonerrors
6Implementations
6.1Heap-based
6.2dlmallocandptmalloc
6.3FreeBSD'sandNetBSD'sjemalloc
6.4OpenBSD'smalloc
6.5Hoardmalloc
6.6mimalloc
6.7Thread-cachingmalloc(tcmalloc)
6.8DFWMalloc
6.9In-kernel
7Overridingmalloc
8Allocationsizelimits
9Extensionsandalternatives
10Seealso
11References
12Externallinks
Rationale[edit]
TheCprogramminglanguagemanagesmemorystatically,automatically,ordynamically.Static-durationvariablesareallocatedinmainmemory,usuallyalongwiththeexecutablecodeoftheprogram,andpersistforthelifetimeoftheprogram;automatic-durationvariablesareallocatedonthestackandcomeandgoasfunctionsarecalledandreturn.Forstatic-durationandautomatic-durationvariables,thesizeoftheallocationmustbecompile-timeconstant(exceptforthecaseofvariable-lengthautomaticarrays[5]).Iftherequiredsizeisnotknownuntilrun-time(forexample,ifdataofarbitrarysizeisbeingreadfromtheuserorfromadiskfile),thenusingfixed-sizedataobjectsisinadequate.
Thelifetimeofallocatedmemorycanalsocauseconcern.Neitherstatic-norautomatic-durationmemoryisadequateforallsituations.Automatic-allocateddatacannotpersistacrossmultiplefunctioncalls,whilestaticdatapersistsforthelifeoftheprogramwhetheritisneededornot.Inmanysituationstheprogrammerrequiresgreaterflexibilityinmanagingthelifetimeofallocatedmemory.
Theselimitationsareavoidedbyusingdynamicmemoryallocation,inwhichmemoryismoreexplicitly(butmoreflexibly)managed,typicallybyallocatingitfromthefreestore(informallycalledthe"heap"),anareaofmemorystructuredforthispurpose.InC,thelibraryfunctionmallocisusedtoallocateablockofmemoryontheheap.Theprogramaccessesthisblockofmemoryviaapointerthatmallocreturns.Whenthememoryisnolongerneeded,thepointerispassedtofreewhichdeallocatesthememorysothatitcanbeusedforotherpurposes.
TheoriginaldescriptionofCindicatedthatcallocandcfreewereinthestandardlibrary,butnotmalloc.CodeforasimplemodelimplementationofastoragemanagerforUnixwasgivenwithallocandfreeastheuserinterfacefunctions,andusingthesbrksystemcalltorequestmemoryfromtheoperatingsystem.[6]The6thEditionUnixdocumentationgivesallocandfreeasthelow-levelmemoryallocationfunctions.[7]Themallocandfreeroutinesintheirmodernformarecompletelydescribedinthe7thEditionUnixmanual.[8][9]
Someplatformsprovidelibraryorintrinsicfunctioncallswhichallowrun-timedynamicallocationfromtheCstackratherthantheheap(e.g.alloca()[10]).Thismemoryisautomaticallyfreedwhenthecallingfunctionends.
Overviewoffunctions[edit]
TheCdynamicmemoryallocationfunctionsaredefinedinstdlib.hheader(cstdlibheaderinC++).[1]
Function
Description
malloc
allocatesthespecifiednumberofbytes
realloc
increasesordecreasesthesizeofthespecifiedblockofmemory,movingitifnecessary
calloc
allocatesthespecifiednumberofbytesandinitializesthemtozero
free
releasesthespecifiedblockofmemorybacktothesystem
Differencesbetweenmalloc()andcalloc()[edit]
malloc()takesasingleargument(theamountofmemorytoallocateinbytes),whilecalloc()needstwoarguments(thenumberofvariablestoallocateinmemory,andthesizeinbytesofasinglevariable).
malloc()doesnotinitializethememoryallocated,whilecalloc()guaranteesthatallbytesoftheallocatedmemoryblockhavebeeninitializedto0.
Onsomeoperatingsystems,calloc()canbeimplementedbyinitiallypointingallpagesoftheallocatedmemory'svirtualaddressestoaread-onlypageofall0s,andonlyallocatingread-writephysicalpageswhenthevirtualaddressesarewrittento,amethodcalledcopy-on-write.
Usageexample[edit]
CreatinganarrayoftenintegerswithautomaticscopeisstraightforwardinC:
intarray[10];
However,thesizeofthearrayisfixedatcompiletime.Ifonewishestoallocateasimilararraydynamically,thefollowingcodecanbeused:
int*array=malloc(10*sizeof(int));
Thiscomputesthenumberofbytesthattenintegersoccupyinmemory,thenrequeststhatmanybytesfrommallocandassignstheresulttoapointernamedarray(duetoCsyntax,pointersandarrayscanbeusedinterchangeablyinsomesituations).
Becausemallocmightnotbeabletoservicetherequest,itmightreturnanullpointeranditisgoodprogrammingpracticetocheckforthis:
int*array=malloc(10*sizeof(int));
if(array==NULL){
fprintf(stderr,"mallocfailed\n");
return-1;
}
Whentheprogramnolongerneedsthedynamicarray,itmusteventuallycallfreetoreturnthememoryitoccupiestothefreestore:
free(array);
Thememorysetasidebymallocisnotinitializedandmaycontaincruft:theremnantsofpreviouslyusedanddiscardeddata.Afterallocationwithmalloc,elementsofthearrayareuninitializedvariables.Thecommandcallocwillreturnanallocationthathasalreadybeencleared:
int*array=calloc(10,sizeof(int));
Withreallocwecanresizetheamountofmemoryapointerpointsto.Forexample,ifwehaveapointeractingasanarrayofsize
n
{\displaystylen}
andwewanttochangeittoanarrayofsize
m
{\displaystylem}
,wecanuserealloc.
int*arr=malloc(2*sizeof(int));
arr[0]=1;
arr[1]=2;
arr=realloc(arr,3*sizeof(int));
arr[2]=3;
Notethatreallocmustbeassumedtohavechangedthebaseaddressoftheblock(i.e.ifithasfailedtoextendthesizeoftheoriginalblock,andhasthereforeallocatedanewlargerblockelsewhereandcopiedtheoldcontentsintoit).Therefore,anypointerstoaddresseswithintheoriginalblockarealsonolongervalid.
Typesafety[edit]
mallocreturnsavoidpointer(void*),whichindicatesthatitisapointertoaregionofunknowndatatype.TheuseofcastingisrequiredinC++duetothestrongtypesystem,whereasthisisnotthecaseinC.Onemay"cast"(seetypeconversion)thispointertoaspecifictype:
int*ptr,*ptr2;
ptr=malloc(10*sizeof(*ptr));/*withoutacast*/
ptr2=(int*)malloc(10*sizeof(*ptr));/*withacast*/
Thereareadvantagesanddisadvantagestoperformingsuchacast.
Advantagestocasting[edit]
IncludingthecastmayallowaCprogramorfunctiontocompileasC++.
Thecastallowsforpre-1989versionsofmallocthatoriginallyreturnedachar*.[11]
Castingcanhelpthedeveloperidentifyinconsistenciesintypesizingshouldthedestinationpointertypechange,particularlyifthepointerisdeclaredfarfromthemalloc()call(althoughmoderncompilersandstaticanalyserscanwarnonsuchbehaviourwithoutrequiringthecast[12]).
Disadvantagestocasting[edit]
UndertheCstandard,thecastisredundant.
Addingthecastmaymaskfailuretoincludetheheaderstdlib.h,inwhichthefunctionprototypeformallocisfound.[11][13]Intheabsenceofaprototypeformalloc,theC90standardrequiresthattheCcompilerassumemallocreturnsanint.Ifthereisnocast,C90requiresadiagnosticwhenthisintegerisassignedtothepointer;however,withthecast,thisdiagnosticwouldnotbeproduced,hidingabug.Oncertainarchitecturesanddatamodels(suchasLP64on64-bitsystems,wherelongandpointersare64-bitandintis32-bit),thiserrorcanactuallyresultinundefinedbehaviour,astheimplicitlydeclaredmallocreturnsa32-bitvaluewhereastheactuallydefinedfunctionreturnsa64-bitvalue.Dependingoncallingconventionsandmemorylayout,thismayresultinstacksmashing.Thisissueislesslikelytogounnoticedinmoderncompilers,asC99doesnotpermitimplicitdeclarations,sothecompilermustproduceadiagnosticevenifitdoesassumeintreturn.
Ifthetypeofthepointerischangedatitsdeclaration,onemayalsoneedtochangealllineswheremallociscalledandcast.
Commonerrors[edit]
Theimproperuseofdynamicmemoryallocationcanfrequentlybeasourceofbugs.Thesecanincludesecuritybugsorprogramcrashes,mostoftenduetosegmentationfaults.
Mostcommonerrorsareasfollows:[14]
Notcheckingforallocationfailures
Memoryallocationisnotguaranteedtosucceed,andmayinsteadreturnanullpointer.Usingthereturnedvalue,withoutcheckingiftheallocationissuccessful,invokesundefinedbehavior.Thisusuallyleadstocrash(duetotheresultingsegmentationfaultonthenullpointerdereference),butthereisnoguaranteethatacrashwillhappensorelyingonthatcanalsoleadtoproblems.
Memoryleaks
Failuretodeallocatememoryusingfreeleadstobuildupofnon-reusablememory,whichisnolongerusedbytheprogram.Thiswastesmemoryresourcesandcanleadtoallocationfailureswhentheseresourcesareexhausted.
Logicalerrors
Allallocationsmustfollowthesamepattern:allocationusingmalloc,usagetostoredata,deallocationusingfree.Failurestoadheretothispattern,suchasmemoryusageafteracalltofree(danglingpointer)orbeforeacalltomalloc(wildpointer),callingfreetwice("doublefree"),etc.,usuallycausesasegmentationfaultandresultsinacrashoftheprogram.Theseerrorscanbetransientandhardtodebug–forexample,freedmemoryisusuallynotimmediatelyreclaimedbytheOS,andthusdanglingpointersmaypersistforawhileandappeartowork.
Inaddition,asaninterfacethatprecedesANSICstandardization,mallocanditsassociatedfunctionshavebehaviorsthatwereintentionallylefttotheimplementationtodefineforthemselves.Oneofthemisthezero-lengthallocation,whichismoreofaproblemwithreallocsinceitismorecommontoresizetozero.[15]AlthoughbothPOSIXandtheSingleUnixSpecificationrequireproperhandlingof0-sizeallocationsbyeitherreturningNULLorsomethingelsethatcanbesafelyfreed,[16]notallplatformsarerequiredtoabidebytheserules.Amongthemanydouble-freeerrorsthatithasledto,the2019WhatsAppRCEwasespeciallyprominent.[17]Awaytowrapthesefunctionstomakethemsaferisbysimplycheckingfor0-sizeallocationsandturningthemintothoseofsize1.(ReturningNULLhasitsownproblems:itotherwiseindicatesanout-of-memoryfailure.Inthecaseofreallocitwouldhavesignaledthattheoriginalmemorywasnotmovedandfreed,whichagainisnotthecaseforsize0,leadingtothedouble-free.)[18]
Implementations[edit]
Theimplementationofmemorymanagementdependsgreatlyuponoperatingsystemandarchitecture.Someoperatingsystemssupplyanallocatorformalloc,whileotherssupplyfunctionstocontrolcertainregionsofdata.ThesamedynamicmemoryallocatorisoftenusedtoimplementbothmallocandtheoperatornewinC++.[19]
Heap-based[edit]
Seealso:sbrk
Implementationoftheallocatoriscommonlydoneusingtheheap,ordatasegment.Theallocatorwillusuallyexpandandcontracttheheaptofulfillallocationrequests.
Theheapmethodsuffersfromafewinherentflaws,stemmingentirelyfromfragmentation.Likeanymethodofmemoryallocation,theheapwillbecomefragmented;thatis,therewillbesectionsofusedandunusedmemoryintheallocatedspaceontheheap.Agoodallocatorwillattempttofindanunusedareaofalreadyallocatedmemorytousebeforeresortingtoexpandingtheheap.Themajorproblemwiththismethodisthattheheaphasonlytwosignificantattributes:base,orthebeginningoftheheapinvirtualmemoryspace;andlength,oritssize.Theheaprequiresenoughsystemmemorytofillitsentirelength,anditsbasecanneverchange.Thus,anylargeareasofunusedmemoryarewasted.Theheapcanget"stuck"inthispositionifasmallusedsegmentexistsattheendoftheheap,whichcouldwasteanyamountofaddressspace.Onlazymemoryallocationschemes,suchasthoseoftenfoundintheLinuxoperatingsystem,alargeheapdoesnotnecessarilyreservetheequivalentsystemmemory;itwillonlydosoatthefirstwritetime(readsofnon-mappedmemorypagesreturnzero).Thegranularityofthisdependsonpagesize.
dlmallocandptmalloc[edit]
DougLeahasdevelopedthepublicdomaindlmalloc("DougLea'sMalloc")asageneral-purposeallocator,startingin1987.TheGNUClibrary(glibc)isderivedfromWolframGloger'sptmalloc("pthreadsmalloc"),aforkofdlmallocwiththreading-relatedimprovements.[20][21][22]AsofNovember2019,thelatestversionofdlmallocisversion2.8.6fromAugust2012.[23]
dlmallocisaboundarytagallocator.Memoryontheheapisallocatedas"chunks",an8-bytealigneddatastructurewhichcontainsaheader,andusablememory.Allocatedmemorycontainsan8-or16-byteoverheadforthesizeofthechunkandusageflags(similartoadopevector).Unallocatedchunksalsostorepointerstootherfreechunksintheusablespacearea,makingtheminimumchunksize16byteson32-bitsystemsand24/32(dependsonalignment)byteson64-bitsystems.[21][23]: 2.8.6,Minimumallocatedsize
Unallocatedmemoryisgroupedinto"bins"ofsimilarsizes,implementedbyusingadouble-linkedlistofchunks(withpointersstoredintheunallocatedspaceinsidethechunk).Binsaresortedbysizeintothreeclasses:[21][23]: Overlaiddatastructures
Forrequestsbelow256bytes(a"smallbin"request),asimpletwopowerbestfitallocatorisused.Iftherearenofreeblocksinthatbin,ablockfromthenexthighestbinissplitintwo.
Forrequestsof256bytesorabovebutbelowthemmapthreshold,dlmallocsincev2.8.0useanin-placebitwisetriealgorithm("treebin").Ifthereisnofreespacelefttosatisfytherequest,dlmalloctriestoincreasethesizeoftheheap,usuallyviathebrksystemcall.Thisfeaturewasintroducedwayafterptmallocwascreated(fromv2.7.x),andasaresultisnotapartofglibc,whichinheritstheoldbest-fitallocator.
Forrequestsabovethemmapthreshold(a"largebin"request),thememoryisalwaysallocatedusingthemmapsystemcall.Thethresholdisusually256 KB.[24]Themmapmethodavertsproblemswithhugebufferstrappingasmallallocationattheendaftertheirexpiration,butalwaysallocatesanentirepageofmemory,whichonmanyarchitecturesis4096bytesinsize.[25]
GamedeveloperAdrianStonearguesthatdlmalloc,asaboundary-tagallocator,isunfriendlyforconsolesystemsthathavevirtualmemorybutdonothavedemandpaging.Thisisbecauseitspool-shrinkingandgrowingcallbacks(sysmalloc/systrim)cannotbeusedtoallocateandcommitindividualpagesofvirtualmemory.Intheabsenceofdemandpaging,fragmentationbecomesagreaterconcern.[26]
FreeBSD'sandNetBSD'sjemalloc[edit]
SinceFreeBSD7.0andNetBSD5.0,theoldmallocimplementation(phkmallocbyPoul-HenningKamp)wasreplacedbyjemalloc,writtenbyJasonEvans.Themainreasonforthiswasalackofscalabilityofphkmallocintermsofmultithreading.Inordertoavoidlockcontention,jemallocusesseparate"arenas"foreachCPU.Experimentsmeasuringnumberofallocationspersecondinmultithreadingapplicationhaveshownthatthismakesitscalelinearlywiththenumberofthreads,whileforbothphkmallocanddlmallocperformancewasinverselyproportionaltothenumberofthreads.[27]
OpenBSD'smalloc[edit]
OpenBSD'simplementationofthemallocfunctionmakesuseofmmap.Forrequestsgreaterinsizethanonepage,theentireallocationisretrievedusingmmap;smallersizesareassignedfrommemorypoolsmaintainedbymallocwithinanumberof"bucketpages,"alsoallocatedwithmmap.[28][better source needed]Onacalltofree,memoryisreleasedandunmappedfromtheprocessaddressspaceusingmunmap.ThissystemisdesignedtoimprovesecuritybytakingadvantageoftheaddressspacelayoutrandomizationandgappagefeaturesimplementedaspartofOpenBSD'smmapsystemcall,andtodetectuse-after-freebugs—asalargememoryallocationiscompletelyunmappedafteritisfreed,furtherusecausesasegmentationfaultandterminationoftheprogram.
Hoardmalloc[edit]
Mainarticle:Hoardmemoryallocator
Hoardisanallocatorwhosegoalisscalablememoryallocationperformance.LikeOpenBSD'sallocator,Hoardusesmmapexclusively,butmanagesmemoryinchunksof64kilobytescalledsuperblocks.Hoard'sheapislogicallydividedintoasingleglobalheapandanumberofper-processorheaps.Inaddition,thereisathread-localcachethatcanholdalimitednumberofsuperblocks.Byallocatingonlyfromsuperblocksonthelocalper-threadorper-processorheap,andmovingmostly-emptysuperblockstotheglobalheapsotheycanbereusedbyotherprocessors,Hoardkeepsfragmentationlowwhileachievingnearlinearscalabilitywiththenumberofthreads.[29]
mimalloc[edit]
Mainarticle:mimalloc
Anopen-sourcecompactgeneral-purposememoryallocatorfromMicrosoftResearchwithfocusonperformance.[30]Thelibraryisabout11,000linesofcode.
Thread-cachingmalloc(tcmalloc)[edit]
Everythreadhasathread-localstorageforsmallallocations.Forlargeallocationsmmaporsbrkcanbeused.TCMalloc,amallocdevelopedbyGoogle,[31]hasgarbage-collectionforlocalstorageofdeadthreads.TheTCMallocisconsideredtobemorethantwiceasfastasglibc'sptmallocformultithreadedprograms.[32][33]
DFWMalloc[edit]
Ahighly-configurablemalloclibraryemployinglock-freefunctionality,DFWMallocisdesignedforenterpriseenvironmentstoberobustagainstfragmentationandallowrun-timeinspectionoftheallocationspace.
In-kernel[edit]
Operatingsystemkernelsneedtoallocatememoryjustasapplicationprogramsdo.TheimplementationofmallocwithinakerneloftendifferssignificantlyfromtheimplementationsusedbyClibraries,however.Forexample,memorybuffersmightneedtoconformtospecialrestrictionsimposedbyDMA,orthememoryallocationfunctionmightbecalledfrominterruptcontext.[34]Thisnecessitatesamallocimplementationtightlyintegratedwiththevirtualmemorysubsystemoftheoperatingsystemkernel.
Overridingmalloc[edit]
Becausemallocanditsrelativescanhaveastrongimpactontheperformanceofaprogram,itisnotuncommontooverridethefunctionsforaspecificapplicationbycustomimplementationsthatareoptimizedforapplication'sallocationpatterns.TheCstandardprovidesnowayofdoingthis,butoperatingsystemshavefoundvariouswaystodothisbyexploitingdynamiclinking.Onewayistosimplylinkinadifferentlibrarytooverridethesymbols.Another,employedbyUnixSystemV.3,istomakemallocandfreefunctionpointersthatanapplicationcanresettocustomfunctions.[35]
Allocationsizelimits[edit]
Thelargestpossiblememoryblockmalloccanallocatedependsonthehostsystem,particularlythesizeofphysicalmemoryandtheoperatingsystemimplementation.
Theoretically,thelargestnumbershouldbethemaximumvaluethatcanbeheldinasize_ttype,whichisanimplementation-dependentunsignedintegerrepresentingthesizeofanareaofmemory.IntheC99standardandlater,itisavailableastheSIZE_MAXconstantfrom.AlthoughnotguaranteedbyISOC,itisusually2^(CHAR_BIT*sizeof(size_t))-1.
Onglibcsystems,thelargestpossiblememoryblockmalloccanallocateisonlyhalfthissize,namely2^(CHAR_BIT*sizeof(ptrdiff_t)-1)-1.[36]
Extensionsandalternatives[edit]
TheClibraryimplementationsshippingwithvariousoperatingsystemsandcompilersmaycomewithalternativesandextensionstothestandardmallocinterface.Notableamongtheseis:
alloca,whichallocatesarequestednumberofbytesonthecallstack.Nocorrespondingdeallocationfunctionexists,astypicallythememoryisdeallocatedassoonasthecallingfunctionreturns.allocawaspresentonUnixsystemsasearlyas32/V(1978),butitsusecanbeproblematicinsome(e.g.,embedded)contexts.[37]Whilesupportedbymanycompilers,itisnotpartoftheANSI-Cstandardandthereforemaynotalwaysbeportable.Itmayalsocauseminorperformanceproblems:itleadstovariable-sizestackframes,sothatbothstackandframepointersneedtobemanaged(withfixed-sizestackframes,oneoftheseisredundant).[38]Largerallocationsmayalsoincreasetheriskofundefinedbehaviorduetoastackoverflow.[39]C99offeredvariable-lengtharraysasanalternativestackallocationmechanism –however,thisfeaturewasrelegatedtooptionalinthelaterC11standard.
POSIXdefinesafunctionposix_memalignthatallocatesmemorywithcaller-specifiedalignment.Itsallocationsaredeallocatedwithfree,[40]sotheimplementationusuallyneedstobeapartofthemalloclibrary.
Seealso[edit]
Bufferoverflow
Memorydebugger
Memoryprotection
Pagesize
Variable-lengtharray
References[edit]
^abISO/IEC9899:1999specification(PDF).p.313,§7.20.3"Memorymanagementfunctions".
^Godse,AtulP.;Godse,DeepaliA.(2008).AdvancedCProgramming.p.6-28:TechnicalPublications.p. 400.ISBN 978-81-8431-496-0.{{citebook}}:CS1maint:location(link)
^Summit,Steve."Chapter11:MemoryAllocation".CProgrammingNotes.Retrieved2020-07-11.
^Stroustrup,Bjarne(2008).Programming:PrinciplesandPracticeUsingC++.1009,§27.4Freestore:AddisonWesley.p. 1236.ISBN 978-0-321-54372-1.{{citebook}}:CS1maint:location(link)
^"gccmanual".gnu.org.Retrieved2008-12-14.
^BrianW.Kernighan,DennisM.Ritchie,TheCProgrammingLanguage,Prentice-Hall,1978;Section7.9(page156)describescallocandcfree,andSection8.7(page173)describesanimplementationforallocandfree.
^alloc(3) – Version6UnixProgrammer'sManual
^malloc(3) – Version7UnixProgrammer'sManual
^Anonymous,UnixProgrammer'sManual,Vol.1,HoltRinehartandWinston,1983(copyrightheldbyBellTelephoneLaboratories,1983,1979);Themanpageformallocetc.isgivenonpage275.
^alloca(3) – FreeBSDLibraryFunctionsManual
^ab"Castingmalloc".Cprogramming.com.Retrieved2007-03-09.
^"clang:lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cppSourceFile".clang.llvm.org.Retrieved2018-04-01.
^"comp.lang.cFAQlist·Question7.7b".C-FAQ.Retrieved2007-03-09.
^Reek,Kenneth(1997-08-04).PointersonC(1 ed.).Pearson.ISBN 9780673999863.
^"MEM04-C.Bewareofzero-lengthallocations-SEICERTCCodingStandard-Confluence".wiki.sei.cmu.edu.
^"POSIX.1-2017:malloc".pubs.opengroup.org.Retrieved2019-11-29.
^Awakened(2019-10-02)."Howadouble-freebuginWhatsAppturnstoRCE".Retrieved2019-11-29.
^Felker,Rich(2019-10-03)."Wow.TheWhatsAppRCEwasthewrongbehaviorforrealloc(p,0)somanyimplementationsinsiston.https://twitter.com/ottom6k/status/1179623539726524417…".Twitter.Retrieved2019-11-29.{{citeweb}}:Externallinkin|title=(help)
^Alexandrescu,Andrei(2001).ModernC++Design:GenericProgrammingandDesignPatternsApplied.Addison-Wesley.p. 78.
^"WolframGloger'smallochomepage".malloc.de.Retrieved2018-04-01.
^abcKaempf,Michel(2001)."Vudomalloctricks".Phrack(57):8.Archivedfromtheoriginalon2009-01-22.Retrieved2009-04-29.
^"Glibc:MallocInternals".sourceware.orgTrac.Retrieved2019-12-01.
^abcLee,Doug."AMemoryAllocator".Retrieved2019-12-01.HTTPforSourceCode
^"MallocTunableParameters".GNU.Retrieved2009-05-02.
^Sanderson,Bruce(2004-12-12)."RAM,VirtualMemory,Pagefileandallthatstuff".MicrosoftHelpandSupport.
^Stone,Adrian."TheHoleThatdlmallocCan'tFill".GameAngst.Retrieved2019-12-01.
^Evans,Jason(2006-04-16)."AScalableConcurrentmalloc(3)ImplementationforFreeBSD"(PDF).Retrieved2012-03-18.
^"libc/stdlib/malloc.c".BSDCrossReference,OpenBSDsrc/lib/.
^Berger,E.D.;McKinley,K.S.;Blumofe,R.D.;Wilson,P.R.(November2000).Hoard:AScalableMemoryAllocatorforMultithreadedApplications(PDF).ASPLOS-IX.ProceedingsoftheninthinternationalconferenceonArchitecturalsupportforprogramminglanguagesandoperatingsystems.pp. 117–128.CiteSeerX 10.1.1.1.4174.doi:10.1145/378993.379232.ISBN 1-58113-317-0.
^Microsoftreleasesoptimizedmalloc()asopensource-Slashdot
^TCMallochomepage
^Ghemawat,Sanjay;Menage,Paul;TCMalloc :Thread-CachingMalloc
^Callaghan,Mark(2009-01-18)."HighAvailabilityMySQL:DoublesysbenchthroughputwithTCMalloc".Mysqlha.blogspot.com.Retrieved2011-09-18.
^"kmalloc()/kfree()include/linux/slab.h".People.netfilter.org.Retrieved2011-09-18.
^Levine,JohnR.(2000)[October1999]."Chapter9:Sharedlibraries".LinkersandLoaders.TheMorganKaufmannSeriesinSoftwareEngineeringandProgramming(1 ed.).SanFrancisco,USA:MorganKaufmann.ISBN 1-55860-496-0.OCLC 42413382.Archivedfromtheoriginalon2012-12-05.Retrieved2020-01-12.Code:[1][2]Errata:[3]
^"malloc:makemallocfailwithrequestslargerthanPTRDIFF_MAX".SourcewareBugzilla.2019-04-18.Retrieved2020-07-30.
^"Whyistheuseofalloca()notconsideredgoodpractice?".stackoverflow.com.Retrieved2016-01-05.
^Amarasinghe,Saman;Leiserson,Charles(2010)."6.172PerformanceEngineeringofSoftwareSystems,Lecture10".MITOpenCourseWare.MassachusettsInstituteofTechnology.Archivedfromtheoriginalon2015-06-22.Retrieved2015-01-27.
^"alloca(3)-Linuxmanualpage".man7.org.Retrieved2016-01-05.
^posix_memalign – SystemInterfacesReference,TheSingleUNIXSpecification,Issue7fromTheOpenGroup
Externallinks[edit]
TheWikibookCProgramminghasapageonthetopicof:CProgramming/CReference
WikiversityhaslearningresourcesaboutC/Memory_Management
DefinitionofmallocinIEEEStd1003.1standard
Lea,Doug;Thedesignofthebasisoftheglibcallocator
Gloger,Wolfram;Theptmallochomepage
Berger,Emery;TheHoardhomepage
Douglas,Niall;Thenedmallochomepage
Evans,Jason;Thejemallochomepage
Google;Thetcmallochomepage
SimpleMemoryAllocationAlgorithmsonOSDEVCommunity
Michael,MagedM.;ScalableLock-FreeDynamicMemoryAllocation
Bartlett,Jonathan;Insidememorymanagement–Thechoices,tradeoffs,andimplementationsofdynamicallocation
MemoryReduction(GNOME)wikipagewithmuchinformationaboutfixingmalloc
C99standarddraft,includingTC1/TC2/TC3
SomeusefulreferencesaboutC
ISO/IEC9899–Programminglanguages–C
Understandingglibcmalloc
vteMemorymanagement
Memorymanagementasafunctionofanoperatingsystem
Hardware
Memorymanagementunit(MMU)
Translationlookasidebuffer(TLB)
Input–outputmemorymanagementunit(IOMMU)
Virtualmemory
Demandpaging
Memorypaging
Pagetable
Virtualmemorycompression
Memorysegmentation
Protectedmode
Realmode
Virtual8086mode
x86memorysegmentation
Memoryallocation
dlmalloc
Hoardmalloc
jemalloc
mimalloc
ptmalloc
Manualmemorymanagement
Staticmemoryallocation
Cdynamicmemoryallocation
newanddelete(C++)
Garbagecollection
AutomaticReferenceCounting
Boehmgarbagecollector
Cheney'salgorithm
Concurrentmarksweepcollector
Finalizer
Garbage
Garbage-firstcollector
Mark-compactalgorithm
Referencecounting
Tracinggarbagecollection
Strongreference
Weakreference
Memorysafety
Bufferoverflow
Bufferover-read
Danglingpointer
Stackoverflow
Issues
Fragmentation
Memoryleak
Unreachablememory
Other
Automaticvariable
InternationalSymposiumonMemoryManagement
Region-basedmemorymanagement
Memorymanagement
Virtualmemory
Automaticmemorymanagement
Memorymanagementalgorithms
Memorymanagementsoftware
vteCprogramminglanguage
ANSIC
C99
C11
C17
C2x
EmbeddedC
MISRAC
Features
Functions
Headerfiles
Operators
String
Syntax
Preprocessor
Datatypes
Standardlibrary
Char
FileI/O
Math
Dynamicmemory
String
Time
Variadic
POSIX
Standardlibraryimplementations
Bionic
libhybris
dietlibc
glibc
EGLIBC
klibc
WindowsCRT
musl
Newlib
uClibc
Compilers
ACK
BorlandTurboC
Clang
GCC
ICC
LCC
NorcroftC
PCC
SDCC
TCC
MicrosoftVisualStudio/Express/C++
WatcomC/C++
IDEs
Anjuta
CLion
Code::Blocks
CodeLite
Eclipse
Geany
GNOMEBuilder
KDevelop
MicrosoftVisualStudio
NetBeans
Comparisonwithotherlanguages
CompatibilityofCandC++
ComparisonwithPascal
Descendantlanguages
C++
C#
D
Objective-C
Alef
Limbo
Go
Vala
Category
Retrievedfrom"https://en.wikipedia.org/w/index.php?title=C_dynamic_memory_allocation&oldid=1084583877"
Categories:MemorymanagementMemorymanagementsoftwareCstandardlibraryC++Hiddencategories:CS1maint:locationCS1errors:externallinksArticleswithshortdescriptionShortdescriptionisdifferentfromWikidataUsedmydatesfromMay2021AllarticleslackingreliablereferencesArticleslackingreliablereferencesfromNovember2015ArticleswithexampleCcode
Navigationmenu
Personaltools
NotloggedinTalkContributionsCreateaccountLogin
Namespaces
ArticleTalk
English
Views
ReadEditViewhistory
More
Search
Navigation
MainpageContentsCurrenteventsRandomarticleAboutWikipediaContactusDonate
Contribute
HelpLearntoeditCommunityportalRecentchangesUploadfile
Tools
WhatlinkshereRelatedchangesUploadfileSpecialpagesPermanentlinkPageinformationCitethispageWikidataitem
Print/export
DownloadasPDFPrintableversion
Languages
ČeštinaEspañolفارسیFrançais한국어Italiano日本語NorskbokmålPortuguêsSimpleEnglishСрпски/srpskiTürkçe中文
Editlinks