Memory management in C programsWord格式.docx
《Memory management in C programsWord格式.docx》由会员分享,可在线阅读,更多相关《Memory management in C programsWord格式.docx(20页珍藏版)》请在冰豆网上搜索。
ThereareseveraltechniquesavailableformemorymanagementinC.ManyofthemareusedinNetHack3.4.3;
andevenmoreareusedsomewhereinNetHack4.Inthisblogpost,I'
dliketolookatthemanddiscusstheiradvantagesanddisadvantages.I'
mmostlyconcernedaboutcorrectness,ratherthanefficiency,here;
thatmeansthatunlesstheperformancedifferenceisverylarge,IcaremoreaboutcleancodethanIdoaboutfastcode.
Techniquesforallocatingfixedamountsofmemory
Therearebasicallytwodifferentissueshere:
trackingthelifetimeofmemoryallocations,andensuringthatthey'
retherightsize.Assuch,I'
llstartbylookingatallocationswhosesizeisstaticallyknownatcompiletime,andthenmoveontotechniquesthatcanhandlethesizebeingunknown.
Fixed-sizebuffersonthestack
ProbablythesimplestwaytoallocatememoryinCistouseastackallocation;
ifavariableisdeclaredinsideafunctionwithoutspecifyingstaticorextern,enoughmemoryforthatvariablewillbeallocatedwhenthatvariable'
sscopestarts,andfreedagainwhenthatvariable'
sscopeends(sometimesknownasan"
automaticvariable"
).BecausescopesinCarewell-nested,atypicalCimplementationwillimplementthisviausingastackofmemory;
newlyallocatedvariableswillbegivenspacefromthe"
top"
ofthestack,andthatspacewillbereleasedfromthetopofthestackwhentheyleavescope.("
Top"
isinquotesbecauseit'
sfarfromrareforastacktobeupside-downinC,withthetopbeingtheendwiththelowestmemoryaddress.)
Therearesomemajoradvantages(andsomeminoradvantages)ofdoingthingsthisway:
∙Itdoesnotrequireanyextrastate,beyondthatprovidedbytheimplementation,towork.Quiteoften,memoryallocationschemeswillthemselvesneedmemorytowork,leadingtosomethingofaninfiniteregress.Stackallocationsareoftenusefultoprovidethatmemory.
∙Unlikethevastmajorityofmemoryallocationschemes,itisexception-safewithnoextraeffort:
longjmpisawareofstackallocations,andwillautomaticallyfreethemfromanyscopeitjumpsoutof.(Somecareisneededinthefunctioncontainingsetjmpitself;
anymemorythatneedstopersistpastalongjmpmustbemarkedasvolatile,arequirementsetbythestandardinordertoallowcompilerstooptimizearoundlongjmpcallsmoreeasily.Technicallyspeaking,thememorydoesnotneedtobemarkedasvolatileifitsvaluedoesnotchangebewtweensetjmpandthematchinglongjmp;
inpractice,althoughcompilerscanhandlethiscase,theytendtospewwarnings,soitmakessensetomarkthememoryasvolatileifitisreadafterthelongjmpatall.)
ThismostlydoesnotmatterinNetHack3.4.3,whichdoesnotuseanyexception-likebehaviour(ifsomethinggoeswrong,itcallspanicwhichattemptstoproduceasavefile,andthenexitstheentireprocess,freeingallthememorythatway).However,NetHack4usesexception-likebehaviourinternally(implementedusinglongjmpandsetjmp,becauseCdoesnothavetrueexceptions);
NitroHack(andthusNetHack4)usesexceptionsinordertoexitagamewithoutexitingtheprocess.FromNetHack4.3(thecurrentdevelopmentversion,whichisunreleasedbutavailableusingthesavebreakbranchoftherepository)onwards,theyareusedevenmoreheavily,handlingsituationslikerewindingthegamemid-turn.
∙Itworkscorrectlyinthepresenceofmultithreading,recursion,andasynchronoussignals.
∙ThistechniquedoesnotrequireanyglobalstateapartfromthatmanagedbytheCcompiler;
thus,itisimpossibleto,forinstance,forgettosaveavariablestoredinastackallocation(unlessthesavecodeisrunninginsideascopecontainingit),ortohaveitaccidentallypersistfromonegameintothenext.
∙Ifyourcodedoesendupoverflowingafixed-sizedbuffer,yourprogramisgoingtobeincorrectnomatterwhat,butifthatbufferisallocatedonthestack,itmaximizesthechancethatyourcompilerwillbeabletogeneratecodetocatchthebufferoverflow(especiallyiftheoverflowhappensinacalltoastandardstringmanipulationfunctionlikesprintforstrcat).Itisincrediblyunwisetorelyonthistoprotectyourcodefromexploits,butit'
saratherhelpfulfeaturefordebugging.(Staticallyallocatedmemoryisalmostasgoodinthisrespect,butdynamicallocationsarehopeless.)
Itisthusnosurprisethatstackalloc