Memory management in C programs.docx
- 文档编号:2875766
- 上传时间:2022-11-16
- 格式:DOCX
- 页数:20
- 大小:37.48KB
Memory management in C programs.docx
《Memory management in C programs.docx》由会员分享,可在线阅读,更多相关《Memory management in C programs.docx(20页珍藏版)》请在冰豆网上搜索。
MemorymanagementinCprograms
MemorymanagementinCprograms
OnelargedifferencebetweenCandmostotherprogramminglanguagesisthatinC,youhavetohandlememoryyourselfratherthanhavingagarbagecollectordoitforyou.Ensuringthatmemoryisallocatedatthecorrectmomentisnotverydifficult(andsomethingthatneedstobedonemanuallyinprettymucheverylanguage);thehardpartistoensurethatenoughmemoryisallocated,andtoensurethatthememoryisdeallocatedwhenitisnolongerinuse.
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Memory management in programs
![提示](https://static.bdocx.com/images/bang_tan.gif)