arrays - I'm very confused about malloc() and calloc() on C

文章推薦指數: 80 %
投票人數:10人

int* array tells the compiler to reserve a pointer on the stack (an integer variable that contains a memory address) · malloc(3*sizeof(int)) allocates on the ... Resultsfromthe2022DeveloperSurveyarenowavailable Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore I'mveryconfusedaboutmalloc()andcalloc()onC AskQuestion Asked 11years,7monthsago Modified 6years,1monthago Viewed 84ktimes 31 10 I'vealwaysprogrammedinJava,whichisprobablywhyI'msoconfusedaboutthis: InJavaIdeclareapointer: int[]array andinitializeitorassignitsomememory: int[]array={0,1,0} int[]array=newint[3] Now,inC,it'sallsoconfusing.AtfirstIthoughtitwasaseasyasdeclaringit: intarray[] andinitializingitorassigningitsomememory: intarray[]={0,1,0} intarray[]=malloc(3*sizeof(int)) intarray[]=calloc(3,sizeof(int)) UnlessI'mwrong,alloftheaboveisequivalentJava-C,right? Then,todayImetacodeinwhichIfoundthefollowing: pthread_ttid[MAX_OPS]; andsomelinesbelow,withoutanykindofinitialization... pthread_create(&tid[0],NULL,mou_usuari,(void*)0); Surprisingly(atleasttome),thecodeworks!AtleastinJava,thatwouldreturnanice"NullPointerException"! So,inorder: AmIcorrectwithalloftheJava-C"translations"? Whydoesthatcodework? Isthereanydifferencebetweenusingmalloc(n*sizeof(int))andcalloc(n,sizeof(int))? Thanksinadvance carraysmalloccalloc Share Improvethisquestion Follow editedApr14,2012at16:27 bluehallu askedNov21,2010at12:50 bluehallubluehallu 10.1k99goldbadges4343silverbadges6060bronzebadges Addacomment  |  5Answers 5 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 44 Youcan'tassignmemorytoanarray.Anarrayhasafixedsize,forthewholeofitslifespan.Anarraycanneverbenull.Anarrayisnotapointer. mallocreturnstheaddresstoamemoryblockthatisreservedfortheprogram.Youcan't"assign"that(beingthememoryblock)toanarray,butyoucanstoretheaddressofthismemoryblockinapointer:luckily,arraysubscriptionisdefinedthroughpointers-soyoucan"usepointerslikearrays",e.g. int*ptr=malloc(5*sizeof*ptr); ptr[2]=5;//accessthethirdelement"ofptr" free(ptr);//alwaysfreeattheend Whenyoudeclareanarraywithoutasize(i.e.array[]),itsimplymeansthesizeofthearrayisdeterminedfromtheinitializerlist.Thatis intarray[]={1,2,3,4,5};//isequalto intarray[5]={1,2,3,4,5}; Tryingtodeclareanarraywithoutasizeandwithoutaninitializerisanerror. Thecodepthread_ttid[MAX_OPS];declaresanarraynamedtidoftypepthread_tandofsizeMAX_OPS. Ifthearrayhasautomaticstorage(i.e.declarationisinsideafunctionandnotstatic,notglobal),theneachofthearrayselementshasindeterminatevalue(anditwouldcauseundefinedbehaviortryingtoreadsuchvalue).Luckily,allthatthefunctioncalldoesisthatittakestheaddressofthefirstelementofthearrayasthefirstparameter,andprobablyinitializesit(theelement)insidethefunction. Thedifferenceofcallocandmallocisthatthememoryblockthatcallocreturnsisinitializedtozero.Thatis; int*ptr=calloc(5,sizeof*ptr); //issomewhatequalto int*ptr=malloc(5*sizeof*ptr); memset(ptr,0,5*sizeof*ptr); Thedifferencebetween int*ptr=malloc(5*sizeof*ptr); //and intarray[5]; isthatarrayhasautomaticstorage,(isstoredonstack),andis"released"afteritgoesoutofscope.ptr,however,(isstoredonheap),isdynamicallyallocatedandmustbefreedbytheprogrammer. Share Improvethisanswer Follow editedApr28,2016at21:38 J-a-n-u-s 1,2791515silverbadges1818bronzebadges answeredNov21,2010at13:12 eq-eq- 9,8563535silverbadges3838bronzebadges 3 1 The1stparagraphhassomedangerouslyambiguousassertions.TheOPwasnottryingtoassignmemorytoanarray,hewasattemptingtoassigna(void*),thereturnfrommalloc()toanarray,andifthatarrayhadbeenaint*Array[i],probablyinafor{}loop,itwouldworkfine,andisthebasisforhowdynamic,multidimensionalarraysareallocatedofftheheap.Also,C99supportsvariablesizedarraysallocatedoffthestack,afeaturefewCprogrammersuse,mostpreferringalloca(),myselfincluded.stackoverflow.com/q/1018853/2548100 – user2548100 Jan16,2014at18:55 1 calloc()isprettymuchjustmemset(malloc(n*mysize),0,(n*mysize)).EspeciallybecauseCusesnull-terminatedstrings,calloc()isveryuseful,especiallywhenviewingstringsinadebugger,whichtypicallyshowsthestringonlyuptothenull-terminator.Ifyou'rejuststatingoutwithC,usecallocinsteadofmalloc,itwillsaveyoufrommakingalotofnon-terminatedCstringerrorsthatcanandprobablywillcrashyourprogram.Forproduction/releasecode,usecalloc()onlywhenyouactuallyneedtoinitializethebuffer/array/vectorto(_int8)0. – user2548100 Jan16,2014at19:01 7 Justtowrapthingsup,andforcompleteness,anArrayISapointer.Infact,anyarraynameinCisexactly,preciselyapointertothebaseofthefirstbyteofthe1stobjectinthearray,andnothingmore.ForpeoplecomingfromJava,.Net,etc,it'shelpfultoknowthatCkeepsthetypeofobjects/variablescompletelyseparatefromthestorageallocatedtoholdthem.Thisiswhyyoucancastapointerasanint,createUNIONs,etc.Very,veryflexible,butdangerousfornoobies.Whenyouallocateanintarray,itsjuststorageatalocation.Youcanputanythingyoulikeinthatstorage. – user2548100 Jan16,2014at19:09 Addacomment  |  5 Youaremissingthreeverybasicandtighten(andmisleading!)Ctopics: thedifferencebetweenarrayandpointers thedifferencebetweenstaticanddynamicallocation thedifferencefromdeclaringvariablesonthestackorontheheap Ifyouwriteintarray[]=malloc(3*sizeof(int));youwouldgetacompilationerror(somethinglike'identifier':arrayinitializationneedscurlybraces). Thismeansthatdeclaringanarrayallowsonlystaticinitialization: intarray[]={1,2,3};thatreserves3contiguousintegersonthestack; intarray[3]={1,2,3};whichisthesameasthepreviousone; intarray[3];thatstillreserves3contiguousintegersonthestack,butdoesnotinitializethem(thecontentwillberandomgarbage) intarray[4]={1,2,3};whentheinitializerlistdoesn'tinitializealltheelements,therestaresetto0(C99§6.7.8/19):inthiscaseyou'llget1,2,3,0 Notethatinallthesecasesyouarenotallocatingnewmemory,youarejustusingthememoryalreadycommittedtothestack.Youwouldruninaproblemonlyifthestackisfull(guessit,itwouldbeastackoverflow).Forthisreasondeclaringintarray[];wouldbewrongandmeaningless. Tousemallocyouhavetodeclareapointer:int*array. Whenyouwriteint*array=malloc(3*sizeof(int));youareactuallydoingthreeoperations: int*arraytellsthecompilertoreserveapointeronthestack(anintegervariablethatcontainsamemoryaddress) malloc(3*sizeof(int))allocatesontheheap3contiguousintegersandreturnstheaddressofthefirstone =assignscopiesthatreturnvalue(theaddressofthefirstintegeryouhaveallocated)toyourpointervariable So,tocomebacktoyourquestion: pthread_ttid[MAX_OPS]; isanarrayonthestack,soitdoesn'tneedtobeallocated(ifMAX_OPSis,say,16thenonthestackwillbereservedthenumberofcontiguousbytesneededtofit16pthread_t).Thecontentofthismemorywillbegarbage(stackvariablesarenotinitializedtozero),butpthread_createreturnsavalueinitsfirstparameter(apointertoapthread_tvariable)anddisregardsanypreviouscontent,sothecodeisjustfine. Share Improvethisanswer Follow editedApr29,2016at9:15 answeredNov21,2010at13:42 lornovalornova 6,24588goldbadges4444silverbadges7171bronzebadges 2 5 fortheintarray[4],they'reallinitialized.Whentheinitializerlistdoesn'tinitializealltheelements,therestaresetto0/NULL(C99§6.7.8/19). – MatthewFlaschen Nov21,2010at14:29 Thisisconfusing;"heap"and"dynamicallocation"refertothesamething."staticinitialization"meansinitializingstaticvariables,whichisnotthecasewhentalkingaboutso-called"stack"variables.Thetypeofallocationinintarray[3];insideafunction,is"automaticallocation"(or"stack"informally,somesystemsdon'thaveastack),not"static". – M.M Apr28,2016at21:49 Addacomment  |  1 Coffersstaticmemoryallocationaswellasdynamic-youcanallocatearraysoffthestackorinexecutablememory(managedbythecompiler).ThisisjustthesameashowinJava,youcanallocateanintonthestackoranIntegerontheheap.ArraysinCarejustlikeanyotherstackvariable-theygooutofscope,etc.InC99theycanalsohaveavariablesize,althoughtheycannotberesized. Themaindifferencebetween{}andmalloc/callocisthat{}arraysarestaticallyallocated(don'tneedfreeing)andautomaticallyinitializedforyou,whereasmalloc/callocarraysmustbefreedexplicitlyandyouhavetoinitializethemexplicitly.Butofcourse,malloc/callocarraysdon'tgooutofscopeandyoucan(sometimes)realloc()them. Share Improvethisanswer Follow answeredNov21,2010at13:15 PuppyPuppy 142k3535goldbadges246246silverbadges454454bronzebadges 1 1 Thearraysareonlystaticifoutsideanyfunctionorexplicitlymarkedstatic;otherwisethey'reautomatic – M.M Apr28,2016at21:50 Addacomment  |  0 2-Thisarraydeclarationisstatic: pthread_ttid[MAX_OPS]; Wedon'tneedtoallocatememoryblock,insteadofdynamicallocation: pthread_t*tid=(pthread_t*)malloc(MAX_OPS*sizeof(pthread_t)); Don'tforgettofreethememory: free(tid); 3-Thedifferencebetweenmallocandcallociscallocallocateablockofmemoryforanarrayandinitializesallitsbitsat0. Share Improvethisanswer Follow editedNov21,2010at15:01 answeredNov21,2010at12:59 remy_jourderemy_jourde 19011goldbadge22silverbadges1414bronzebadges 5 Sowhatwouldbethedifferencebetweenthefirstandthesecond?Andwhyareyoucastingtoapointerthesecondline?SorryifIsoundstupid,butthisisallnewtome... – bluehallu Nov21,2010at13:04 Ok,Ijustsawwhyareyoucasting.Still,isthereanypracticaldifferencebetweenthefirstandsecondlineapartfromthatyoucan"move"thepointertoanythingyouwant? – bluehallu Nov21,2010at13:12 Astaticdeclarationissaferthanadynamiconebutyoucan'treallocateyourmemoryblockinordertochangeitssize. – remy_jourde Nov21,2010at13:13 2 Yourmalloccalliswrong.Malloctakesanumberofbytesnotentries. – R..GitHubSTOPHELPINGICE Nov21,2010at13:41 2 YouforgottomultiplyMAX_OPSbysizeof*tidinmalloc(). – AlexBudovski Nov21,2010at13:42 Addacomment  |  -1 IfindithelpfulwhenyouareprogramminginC(asopposedtoC++)toindicate*arrayexplicitly,torememberthatthereisapointerthatcanbemovedaround.SoIwouldliketostartbyrephrasingyourexampleas: intarray[]={0,1,2}; int*array=malloc(3*sizeof(int)); int*array=calloc(3,sizeof(int)); Thefirstmakesitclearthatthereissomethingcalledarraywhichispointingtoablockofmemorythatcontainsa0,1and2.arraycan'tbemovedelesewhere. Yournextcode: pthread_ttid[MAX_OPS]; Doesinfactcauseanarraywithsizeof(pthread_t)*MAX_OPStobeallocated.Butitdoesnotallocateapointercalled*tid.Thereisanaddressofthebaseofthearray,butyoucan'tmoveitelsewhere. Theptherad_ttypeisactuallyacoverforapointer.Sotidaboveisactuallyanarrayofpointers.Andtheyareallstaticallyallocatedbuttheyarenotinitialized. Thepthread_createtakesthelocationatthebeginningofthearray(&tid[0]),whichisapointer,andallocatesablockofmemorytoholdthepthreaddatastructure.Thepointerissettopointtothenewdatastructureandthedatastructureisallocated. Yourlastquestion---thedifferencebetweenmalloc(n*sizeof(int))andcalloc(n,sizeof(int))isthatthelaterinitializeseachbyteto0,whilethefirstdoesnot. Share Improvethisanswer Follow editedNov24,2010at1:34 answeredNov21,2010at12:57 vy32vy32 26.3k3333goldbadges110110silverbadges218218bronzebadges 3 So,ifIdeclare:intarray[]ithasit'smemoryalreadyallocated?It'sthenthesamethandeclaringthepointerandthenusingmalloc?thanksagain – bluehallu Nov21,2010at13:00 @Hallucynogenyc:No,it'snotthesame.intarray[size]isallocatedoffthestack.intarray[]=malloc()isontheheap. – Puppy Nov21,2010at13:15 2 InC,thefirstofthose3linesissimplynotvalid.Itwillnotcompile. – R..GitHubSTOPHELPINGICE Nov21,2010at13:40 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedcarraysmalloccallocoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool AskWizardTestResultsandNextSteps Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Trending:Anewanswersortingoption Linked 465 Whyistheuseofalloca()notconsideredgoodpractice? Related 567 InwhatcasesdoIusemallocand/ornew? 303 Howdomalloc()andfree()work? 877 Differencebetweenmallocandcalloc? 283 Whymalloc+memsetisslowerthancalloc? 7 Writingtopointeroutofboundsaftermalloc()notcausingerror 31 DynamicarrayinC—Ismyunderstandingofmallocandrealloccorrect? 7 calloc()slowerthanmalloc()&memset() 1 howtoputaparsedstringinsideofmalloc/calloc/dynamicmemory? 2 C-(malloc,calloc,orstatic)2dchararrayreturnedfromfunction 1 Generatingamatrixwithmallocandcalloccausingconfusingbehavior HotNetworkQuestions WhatisthepurposeofthefuelpumpsintheA320? Formallanguagerewriterules:strangenotation Doesmycathatemenow Iboughtmyfirstroadbike,andithurtsmybackandhands Howareanygunrestrictionsconstitutional? Hypothetically,canearlyhumansdomesticategiantantssimilartowolves?Maybeevenassistthemintheagriculturalrevolution? HowdoIsetvaluenodeto#frameusingpython JustificationforaMagicschoolbeingdangerous Wouldasolarsystemwithfourearthsdirectlyoppositetoeachotherhavedifferentflora? HowcanIaddalayerofmeaningtoanevilcampaign? Willmymeatloafcookifthesauceismixedintothemeat Howtoreplaceantidiagonalelementsofamatrix Whycan'tItakephotosinsideofstoresinPortugal? Howwouldyoustandardizeon-callexpectationsacrosssoftwareteamswhenthey'vedivergedatthesamesalarylevel? IsDatafromStarTrekabletoswim? IssoundofUSSEnterprise’sautomaticdooropeningindeedtoiletflushingsound? Howlongcanmycharactersurvivewithoutsleep? SeparationoftheChurchandStateinHinduism Howmakingonlysmallhillsflatterinlandscape? Doestheemailsizelimitincludethesizeofthebody? Expectedvalueof100briefcaseseachwith1dollarexceptfor1thatresetsyouraccumulatedamounttozero? WhatarethecorrectspecsforanSNESpowersupply? Uglyshadowglitch HowcanIremovemarkerswithnumbers2,5,7? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?