Dynamic Memory Allocation1

Embed Size (px)

Citation preview

  • 7/31/2019 Dynamic Memory Allocation1

    1/5

    Lesson6:DynamicMemoryAllocation

    Step1-AnIntroductiontoDynamicMemoryAllocation

    Upuntilthistime,wehaveusedwhatisreferredtoasstaticmemory.Staticmemorymeanswereserveacertainamountofmemorybydefaultinsideourprogramtouseforvariablesandsuch.Whilethereisnothingwrongwiththis,itmeansthatoncewereservethismemory,nootherprogramcanuseit,evenifwearenotusingitatthetime.So,ifwehavetwoprogramsthatreserve1000bytesofmemoryeach,butneitherprogramisrunning,thenwehave2000bytesofmemorythatisbeingcompletelywasted.Supposeweonlyhave3000bytesofmemory,butwealreadyhaveourtwoprogramsthattake1000byteseach.Nowwewanttoloadaprogramthatneeds1500bytesofmemory.Well,wejusthitawall,becauseweonlyhave3000bytesofmemoryand2000bytesarealreadyreserved.Wecan'tloadourthirdprogrameventhoughwehave2000bytesofmemorythatisn'tevenbeingused.Howcouldwepossiblyremedythissituation?

    IfyousaidDynamicMemoryAllocation,thenyoumusthavereadthetitleofthislesson.That'sright.Wearegoingtousedynamicmemorytosharethememoryamongallthreeprograms.

    Dynamicmemorywon'tfixeverything.Wewillalwaysneedanamountoffinitestaticmemory,butthisamountisusuallymuchlessthanweneed.Thisiswhywestillhavestaticmemory.

    So,letusimagineanewscenario.Wehavechangedourfirsttwoprogramstousedynamicmemoryallocation.Nowtheyonlyneedtoreserve100bytesofmemoryeach.Thismeanswearenowonlyusing200bytesofour3000totalmemorybytesavailable.Ourthirdprogram,whichrequires1500bytesofmemorycannowrunfine.

    Step2-TheBasicsofDynamicMemoryAllocation

    Nowthatwehavecoveredwhywewouldwanttousedynamicmemoryallocation,howdowegoaboutdoingit?Well,that'seasy!Wehavepredefinedfunctionsthatletusperformthesetasks.

    Thetwofunctionswewillbeemployinginourdynamicmemoryallocationtasksaremalloc()andfree().malloc()meaningmemoryallocation,andfree,well,thatshouldbeobvious.Ourmalloc()functionreturnsapointertothememoryblockwerequested.Rememberpointersfromthelastlesson?Itoldyouweweren'tdonewiththemyet.

    Let'sdiscussthesyntaxofmalloc().Ittakesasingleargument,alongintegerrepresentingthenumberofbyteswewanttoallocatefromtheheap.(Note:theheapiswhatwecallallthememorywedon'treservebydefault)So,forexample,toallocatememoryforanarrayofcharactersfora40characterstring,wewoulddomalloc(40);There'smoretoit,obviously,butwe'llcoverthat.

    Toallocatememorythough,wemusthaveapointersowecanknowwherethem

    emorywillbeatwhenitgetsallocated.Let'slookatasmallcodeexample:

    char*str=(char*)malloc(40); //allocatememoryfora40characterstring

    Thismaylookalittleweird,becauseitusesaconceptwehaven'tworkedwithbeforecalled"typecasting".Chastheabilitytoconvertfromonetypeofvariabletoanotherbyusingwhatarecalledtypecastoperators.Thesyntaxissimple,putthevariabletypeyouwanttoconverttoinsideparentheses.See,it'seasy.So,becausewewanttoconvertthememoryintoacharacterpointer,whic

  • 7/31/2019 Dynamic Memory Allocation1

    2/5

    hisspecifiedbythetypechar*,weputchar*inparentheses.ThenCwillgiveusacharacterpointertothememory.Thisisveryeasytodowhenacharacterpointerisinvolved.Theimportantthingtonotehereiswhatmalloc()returnstous.Becausemalloc()doesn'tcarehowthememoryweallocatewillbeused,malloc()justreturnsapointertoaseriesofbytes.Itdoesthisbyusingavoidpointer.Voidpointersarejustlikecharacterpointers,orintegerpointers,oranyotherkindofpointerwithonespecialdifference:wedonotknowwhatthesizeofthevoidpointeris.Thereisnowaytoincrementordecrementavoidpointer.Infact,wecan'tdomuchofanythingwithavoidpointerexceptacknowledgeitsexistenceuntilweconvert(typecast)ittoanothervariabletype.

    Charactersarebydefinition1byte,andmallocalwaysallocatesinmultiplesofasinglebyte.Othertypesaremorethan1byte.Ratherthanrememberinghowmanybytesanintvariabletakesonasystem,wecanusethesizeofoperator.Let'sseeanexample.

    char*str=(char*)malloc(40*sizeof(char)); //allocatememoryfora40characterstring

    Thislooksverysimilartowhatwehadabove,withoneimportantexception,thesizeof(char)multiplier.Thisisanewoperator,andanotherveryimportantoneinC.Thesizeof()operatorwilltellusthesizeofanyvariableorstructureinourprogram.Theonethingtokeepinmindwhenusingsizeof()isthatthesizeofapointerishowmanybytesittakestostorethepointer,notthesize

    ofthememoryblockthepointerispointingat.Thereisnoneedtoknowthatinformation.Inallocatingmemorylikethis,weknowwehave40charactersinsteadof40bytes(eventhoughtheyaretechnicallythesame).Thereisadifferencebetween40integersand40bytes,and40longintegersespecially.

    Nowthatwehavetakenalookathowthemalloc()functionworks,let'stakealookatitscompanionfunction,free().Thefree()functionisbasicallytheexactoppositeofmalloc().So,insteadofassigningapointerthevaluereturned,wegivethefunctionthepointerwegotfrommalloc().So,ifwehavethe*strpointerweallocatedabove,tofreethatmemory,wejustneedtocallfreewiththepointerasanargument.

    free(str); //freethememoryallocatedbymalloc()

    Youmaybewonderinghowthefree()functionknowshowmuchmemorytofreeup,sincewedidn'ttellithowmuchmemoryweallocated.Well,theshortansweris:youdon'tneedtoworryaboutthat.Thesystemwilltakecareofsuchminutiaforus.Thelongansweris,well,long,andcomplicated,soIdon'twanttotalkaboutit.

    Mostmodernsystemswillfreeallocatedmemoryatthecompletionoftheprogram.TheAMSisnotoneofthesesystems.Ifyoudon'tfreethememoryyouallocate,yourcalculatorwilllosememoryuntilitisreset.

    Step3-TheManyUsesofmalloc()

    StartTIGCCandcreateanewproject.CreateanewCSourceFilecalledmalloc.Editthefilesothatitlookslikethis:

    malloc.c

    #include

    void_main(void){intloop;unsignedlongint*array;//theintegerarraypointer

  • 7/31/2019 Dynamic Memory Allocation1

    3/5

    //clearthescreenforprintf()clrscr();

    //allocatethearrayorexitwithanerrorif((array=(unsignedlongint*)malloc(45*sizeof(unsignedlongint)))==NULL){DlgMessage("DMAFailure","Unabletoallocateintegerarrayspace",BT_OK,BT_NONE);return;}

    //getthefirsttwonumbersintheFibonaccisequence--Istartat1,not0array[0]=1;array[1]=1;

    //setupthearraywiththefirst45numbersinthesequencefor(loop=2;loop

  • 7/31/2019 Dynamic Memory Allocation1

    4/5

    unsignedlongint*array; //theintegerarraypointer

    Wehaveourvariabledeclarations.Rememberthatthereisverylittledifferencebetweenarraysandpointers,sooncewehavespaceforourpointer,itwillbeanarray.

    //allocatethearrayorexitwithanerrorif((array=(unsignedlongint*)malloc(45*sizeof(unsignedlongint)))==NULL){ DlgMessage("DMAFailure","Unabletoallocateintegerarrayspace",BT_OK,BT_NONE); return;}

    OnethingIforgottomentionaboutDynamicMemoryAllocationis,unlikestaticmemorywhichisreservedbydefault(soyouwon'tbeabletosendtheprogramunlessyouhaveenoughmemory),dynamicmemorymustbeallocatedatruntime.Thatbeingsaid,theremaynotbeenoughmemoryavailabletofilltherequest.So,wemustalwayscheckthatourmemorywasactuallyallocatedtousbycheckingthepointeragainstaNULLvalue.TheNULLvaluebasicallysays,"Iamnotpointingatanything".And,ifwearenotpointingatanythingafterwefinishourmalloc()call,thenwedon'thaveenoughmemorytorunthisprogram.Weshoulddisplaysomekindoferrormessageandexittheprogram.

    Toexitaprogramfromthemain()method,wecanusethereturnkeyword.Youhaveseenreturnwhenwearesendingbackavaluefromafunction.Themainfunctionisnodifferent,exceptthatwedonotreturnavaluebecausethereturntypeofthemainfunctionisvoid.So,wecanusereturnwithoutreturninganyspecificvalue.

    Thisbeingdone,ifwehaven'texitedourprogram,thenwemusthavegottenthememorywerequested.So,letuscontinue.

    //getthefirsttwonumbersintheFibonaccisequence--Istartat1,not0array[0]=1;array[1]=1;

    SincethisexampledealswiththeFibonacciSequence,weneedtoinitializethebasecasesofthatsequence.Ifyouhaven'tseentheFibonaccisequencebefore,itrunslikethis.Thefirsttwonumbersare1and1.Everynumberafterthefirsttwonumbersarethesumoftheprevioustwonumbers.Sowehave1,1,2(1+1),3(1+2),5(2+3),8(3+5),13(5+8),etc.Rememberthatsincearraysarejustaspecialwayofusingpointers,wecanusearraynotationforaccessingourpointermemory.Wecouldhavedonethesamethingbyusingthiscode:

    *array=1; //setthefirstarraynodeto1*++array=1;//setthesecondarraynodeto1

    Butarraynotationismorereadable.

    //setupthearraywiththefirst45numbersinthesequencefor(loop=2;loop

  • 7/31/2019 Dynamic Memory Allocation1

    5/5

    gnmentstatement(=).

    //displaytheintromessageprintf("TheFibonacciSequence:\n");printf("Pressakeytobegin!\n\n");ngetchx();

    Youshouldknowhowprintf()worksbynow,especiallyinthislimitedexample.Wearejustdisplayingashortmessageonthescreen.

    //loopthroughthearrayandprintoutthenumbersinthesequencefor(loop=0;loop