百科游戏 手游攻略
知识点9:动态内存分配(dynamic memory allocation)
Dynamicmemoryallocationsortofallowsustheway
togetaroundthisparticularproblem:
Wecanusepointerstogetaccesstodynamicallyallocatedmemory,memorythatisallocatedasyourprogramisrunning.It'snotallocatedatcompiletime.
Whenyoudynamicallyallocatememoryitcomesfromapoolofmemoryknownastheheap.
Previouslyallthememorywe'vebeenworkingwithinthecoursehasbeencomingfromapoolofmemoryknownasthestack.
Agoodwaytogenerallykeepinmindisthatanytimeyougiveavariableaname,itprobablylivesonthestack.
Andanytimeyoudon'tgiveavariableaname,whichyoucandowithdynamicmemoryallocation,itlivesontheheap.
NowI'mkindofpresentingthisasifthere'sthesetwopoolsofmemory.
thisdiagramisisgenerallyarepresentationofwhatmemorylookslike,andwe'renotgoingtocareaboutallthestuffatthetopandthebottom.
Whatwecareaboutisthispartinthemiddlehere,heapandstack.
Asyoucanseebylookingatthisdiagram,theseactuallyaren'ttwoseparatepoolsofmemory.
It'sonesharedpoolofmemorywhereyoustart,inthisvisualyoustartatthebottomandstartfillingupfromthebottomwiththestack,andyoustartatthetopandstartfillingupfromthetopdownwiththeheap.
Butitreallyisthesamepool,it'sjustdifferentspots,differentlocationsinmemorythatarebeingallocated.
Andyoucanrunoutofmemorybyeitherhavingtheheapgoallthewaytothebottom,orhavethestackgoallthewaytothetop,orhavingtheheapandthestackmeetupagainsteachother.
Allofthosecanbeconditionsthatcauseyourprogramtorunoutofmemory.
Sohowdowegetdynamicallyallocatedmemoryinthefirstplace?Howdoesourprogramgetmemoryasit'srunning?
WellCprovidesafunctioncalledmalloc,memoryallocator,whichyoumakeacallto,andyoupassinhowmanybytesofmemorythatyouwant.
Soifyourprogramisrunningandyouwantanintegerruntime,youmightmallockfourbytesofmemory,mallocparenthesesfour.
mallockwillgothroughlookingthroughtheheap,becausewe'redynamicallyallocatingmemory,anditwillreturntoyouapointertothatmemory.
Itdoesn'tgiveyouthatmemory--itdoesn'tgiveitaname,itgivesyouapointertoit.
Ifmallockcan'tgiveyouanymemorybecauseyou'verunout,it'llgiveyoubackanullpointer.Wesufferasegfault.
Soeverytimeyoumakeacalltomallocyoualways,alwaysneedtocheckwhetherornotthepointeritgaveyoubackisnull.
Ifitis,youneedtoendyourprogrambecauseifyoutryanddereferencethenullpointeryou'regoingtosufferasegmentationfaultandyourprogramisgoingtocrashanyway.
Sohowdowestaticallyobtainaninteger?
intx.
We'veprobablydonethatabunchoftimes,right?
Thiscreatesavariablecalledxthatlivesonthestack.
Howdowedynamicallyobtainaninteger?
Intstarpxequalsmalloc4.
Ormoreappropriatelywe'dsayintstarpxequalsmallocsizeofint,justtothrowsomefewermagicnumbersaroundourprogram.
Thisisgoingtoobtainforusfourbytesofmemoryfromtheheap,andthepointerwegetbacktoitiscalledpx.Andthenjustaswe'vedonepreviouslywecandereferencepxtoaccessthatmemory.
Whatifwewanttocreateanarrayofxfloatsthatliveonthestack?
floatstack_array--that'sthenameofourarray--squarebracketsx.Thatwillcreateforusanarrayofxfloatsthatliveonthestack.
Wecancreateanarrayoffloatsthatlivesontheheap,too.
Thesyntaxmightlookalittlemorecumbersome,butwecansayfloatstarheap_arrayequalsmallocxtimesthesizeofthefloat.Ineedenoughroomtoholdxfloatingpointvalues.
SosayIneed100floats,or1,000floats.Sointhatcaseitwouldbe400bytesfor100floats,or4,000bytesfor1,000floats,becauseeachfloattakesupfourbytesofspace.
AfterdoingthisIcanusethesquarebracketsyntaxonheap_array.
JustasIwouldonstack_array,Icanaccessitselementsindividuallyusingheap_arrayzero,heap_arrayone.ButrecallthereasonwecandothatisbecausethenameofanarrayinCisreallyapointertothatarray'sfirstelement.
Sothefactthatwe'redeclaringanarrayoffloatsonthestackhereisactuallyabitmisleading.Wereallyareinthesecondlineofcodetherealsocreatingapointertoachunkofmemorythatwethendosomeworkwith.
Here'sthebigproblemwithdynamicallyallocatedmemorythough,andthisiswhyit'sreallyimportanttodevelopsomegoodhabitswhenyou'reworkingwithit.
Unlikestaticallydeclaredmemory,yourmemoryisnotautomaticallyreturnedtothesystemwhenyourfunctionisdone.
Soifwehavemain,andmaincallsafunctionf,whenffinisheswhateverit'sdoingandreturnscontroloftheprogrambacktomain,allofthememorythatfusedisgivenback.Itcanbeusedagainbysomeotherprogram,orsomeotherfunctionthatgetscalledlateroninmain.Itcanusethatsamememoryoveragain.
Ifyoudynamicallyallocatememorythoughyouhavetoexplicitlytellthesystemthatyou'redonewithit.It'llholdontoitforyou,whichcouldleadtoaproblemofyourunningoutofmemory.
Andinfactwesometimesrefertothisasamemoryleak.
Andsometimesthesememoryleakscanactuallybereallydevastatingforsystemperformance.
Howdowegivememorybackwhenwe'redonewithit?Wellfortunatelyit'saveryeasywaytodoit.Wejustfreeit.
There'safunctioncalledfree,itacceptsapointertomemory,
Solet'ssaywe'reinthemiddleofourprogram,wewanttomalloc50characters.
Wewanttomallocanarraythatcancapableofholding50characters.Andwhenwegetapointerbacktothat,thatpointer'snameisword.Wedowhateverwe'regoingtodowithword,andthenwhenwe'redonewejustfreeit.Andnowwehavereturnedthose50bytesofmemorybacktothesystem.
Sotherearethreegoldenrulesthatshouldbekeptinmindwheneveryou'redynamicallyallocatingmemorywithmalloc.
Solet'sgothroughanexamplehereofwhatsomedynamicallyallocatedmemorymightlooklikemixedinwithsomestaticmemory.
Sowesayintm.
WhatifIthensayintstara?
SoI'mcoloringitgreen-ishaswell.Iknowithassomethingtodowithaninteger,butit'snotitselfaninteger.
Butit'sprettymuchthesameidea.I'vecreatedabox.Bothoftheserightnowliveonthestack.I'vegiventhembothnames.
Then,intstarbequalsmallocsizeofint.
Wellthisdoesn'tjustcreateonebox.Thisactuallycreatestwoboxes.Anditties(连接在一起),italsoestablishesapointinarelationship.
We'veallocatedoneblockofmemoryontheheap.Noticethatthetoprightboxtheredoesnothaveaname.
Wemallocdit.Itexistsontheheap.Butbhasaname.It'sapointervariablecalledb.Thatlivesonthestack.
Soit'sapieceofmemorythatpointstoanotherone.bcontainstheaddressofthatblockofmemory.Itdoesn'thaveanameotherwise.Butitpointstoit.
Nowwe'llgetlittlemorestraightforwardagain.aequalsampersandm.
Doyourecallwhataequalsampersandmis?Wellthat'sagetsm'saddress.Orputmorediagrammatically,apointstom.
OKsohere'sanotherone.
Aequalsb.
What'sgoingtohappentothediagramthistime?
Wellrecallthattheassignmentoperatorworksbyassigningthevalueontherighttothevalueontheleft.
Soinsteadofapointingtom,anowpointstothesameplacethatbpoints.adoesn'tpointtob,apointswherebpoints.
Ifapointedtobthatwouldhavebeenaequalsampersand(&)b.
Butinsteadaequalsbjustmeansthataandbarenowpointingtothesameaddress,becauseinsideofbisjustanaddress.Andnowinsideofaisthesameaddress.
mequals10,probablythemoststraightforwardthingwe'vedoneinalittlebit.Putthe10inthebox.
Starbequalsmplus2,recallfromourpointersvideowhatstarbmeans.
We'regoingtodereferencebandputsomevalueinthatmemorylocation.Inthiscase12.
Sowhenwedereferenceapointofrecallwejusttraveldownthearrow(遵循着箭头的轨迹).
Orputanotherway,wegotothatmemoryaddressandwemanipulateitinsomeway.Weputsomevalueinthere.
Inthiscasestarbequalsmplus2isjustgotothevariablepointedtobyb,gotothememorypointedtobyb,andputmplus2inthere,12.
NowIfreeb.
WhathappenswhenIfreeb?
I'mdoneworkingwithit,right?Iessentiallygiveupthememory.Igiveitbacktothesystem.Idon'tneedthisanymoreiswhatI'mtellingthem,OK?
NowifIsaystaraequals11youcanprobablyalreadytellthatsomethingbadisgoingtohappenhere,right?AndindeedifItriedthatIprobablywouldsufferasegmentationfault.
Becausenow,althoughpreviouslythatchunkofmemorywassomethingthatIhadaccessto,atthispointnowI'maccessingmemorythatisnotlegalformetoaccess.
Andaswewillprobablyrecall,whenweaccessmemorythatwe'renotsupposedtotouch,that'sthemostcommoncauseofasegmentationfault.AndsomyprogramwouldcrashifItriedtodothis.
结语:
Soagainit'sagoodideatogetgoodpracticeandgoodhabitsingrainedwhenworkingwithmallocandfree,sothatyoudon'tsuffersegmentationfaults,andthatyouuseyourdynamicallyallocatedmemoryresponsibly.
dynamically是什么意思
dynamically
英[daɪˈnæmɪkli]美[daɪˈnæmɪkli]
adv.动态地;充满活力地;不断变化地
短语
dynamicallyequivalentmodel等效动力学模型;等效动力学模子;等效动力学
dynamicallybalanced动平衡的;做过动态平衡的
DynamicallyTypedLanguage动态类型语言;语言
DYNAMICALLYASSIGNEDPORTS端口
DynamicallyAllocated动态分配;使用静态指派空间;动态分配的;动态地分配
dynamicallycast动态地转换
dynamicallybound动态绑定
AdaptDynamically随需而动;动态适应;需而动;详细翻译
DynamicallySwitchable动态切换
双语例句
Theunhamperedmarketisaverydynamicallyefficientprocess.
无阻碍的市场是一个动态高效的过程。
Icanjustwhipoutavariable,andthistimeit'sgonnabedynamicallystoredthere.
我可以拿出一个变量,并且这次它会被动态地存储在那里。
He'soneofthemostdynamicallyimaginativejazzpianistsofourtime.
他是我们这个时代最具活跃想像力的爵士乐钢琴演奏家之一。
linux怎么查看oracle版本
1、命令获取法
以root用户登录系统后,执行‘sqlplus/assysdba’回车,这个时候可以看到oracle数据库的版本。
2、工具获取法,以plsqldeveloper为例。
登录成功后,输入‘select*fromv$version’,点击执行。
在查询结果里即可看到版本信息:
- 上一篇:神奇宝贝小说(神奇宝贝排名前十小说)
- 下一篇:权志龙无限挑战(全总结谢谢)
- 最近发表