C Programming: malloc() inside another function

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

I'm passing a pointer and size to the function from my main() and I would like to allocate memory for that pointer dynamically using malloc() from inside ... 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 CProgramming:malloc()insideanotherfunction AskQuestion Asked 12years,1monthago Modified 2yearsago Viewed 108ktimes 79 75 Ineedhelpwithmalloc()insideanotherfunction. I'mpassingapointerandsizetothefunctionfrommymain()andIwouldliketoallocatememoryforthatpointerdynamicallyusingmalloc()frominsidethatcalledfunction,butwhatIseeisthat....thememory,whichisgettingallocated,isforthepointerdeclaredwithinmycalledfunctionandnotforthepointerwhichisinsidethemain(). HowshouldIpassapointertoafunctionandallocatememoryforthepassedpointerfrominsidethecalledfunction? IhavewrittenthefollowingcodeandIgettheoutputasshownbelow. SOURCE: intmain() { unsignedchar*input_image; unsignedintbmp_image_size=262144; if(alloc_pixels(input_image,bmp_image_size)==NULL) printf("\nPoint2:Memoryallocated:%dbytes",_msize(input_image)); else printf("\nPoint3:Memorynotallocated"); return0; } signedcharalloc_pixels(unsignedchar*ptr,unsignedintsize) { signedcharstatus=NO_ERROR; ptr=NULL; ptr=(unsignedchar*)malloc(size); if(ptr==NULL) { status=ERROR; free(ptr); printf("\nERROR:Memoryallocationdidnotcompletesuccessfully!"); } printf("\nPoint1:Memoryallocated:%dbytes",_msize(ptr)); returnstatus; } PROGRAMOUTPUT: Point1:Memoryallocatedptr:262144bytes Point2:Memoryallocatedinput_image:0bytes cfunctionpointersmalloc Share Improvethisquestion Follow editedMay31,2016at18:17 JonathanLeffler 700k130130goldbadges861861silverbadges12311231bronzebadges askedMay14,2010at22:29 HaggarTheHorribleHaggarTheHorrible 6,7551818goldbadges6666silverbadges7979bronzebadges 0 Addacomment  |  9Answers 9 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 111 HowshouldIpassapointertoa functionandallocatememoryforthe passedpointerfrominsidethecalled function? Askyourselfthis:ifyouhadtowriteafunctionthathadtoreturnanint,howwouldyoudoit? You'deitherreturnitdirectly: intfoo(void) { return42; } orreturnitthroughanoutputparameterbyaddingalevelofindirection(i.e.,usinganint*insteadofint): voidfoo(int*out) { assert(out!=NULL); *out=42; } Sowhenyou'rereturningapointertype(T*),it'sthesamething:youeitherreturnthepointertypedirectly: T*foo(void) { T*p=malloc(...); returnp; } oryouaddonelevelofindirection: voidfoo(T**out) { assert(out!=NULL); *out=malloc(...); } Share Improvethisanswer Follow editedOct25,2014at20:12 answeredMay14,2010at23:17 jamesdlinjamesdlin 66.4k1313goldbadges131131silverbadges159159bronzebadges 5 3 ThanksforgivingtheexplanationIwastoorushedtoprovide. – MarkRansom May15,2010at1:44 +1,Iloveeverythingbuttheassertion,howeveritsfineforsuchasimpledemonstration. – TimPost ♦ May15,2010at6:47 1 Iliketheassertion;itisapartofthecontractforthefunctionwhichthecallershouldgetsystematicallycorrect.Ofcourse,evenmoresubtlecodemightmakeaNULLoutallowable,havingitcorrespondtoanoptionalout-parameter.Butthat'snotwhatisneededforalloc_pixels;thequestiondoesnotrequiresuchsophistication. – DonalFellows May15,2010at6:56 1 Isitsafetofree(*out)insidethecallingfunction(maininthiscase)? – WilliamEverett Jan9,2014at16:51 2 @Pinyaka:It'ssafeforthecallertocallfree()ontheresultingpointer(howelsewouldthecallerfreetheallocatedmemory?).However,thecallerwouldeitherbedoingT*out=foo();(inthefirstform)orT*out;foo(&out);(inthesecondform).Inbothcases,thecallerwouldhavetocallfree(out),notfree(*out). – jamesdlin Jan9,2014at17:29 Addacomment  |  88 Youneedtopassapointertoapointerastheparametertoyourfunction. intmain() { unsignedchar*input_image; unsignedintbmp_image_size=262144; if(alloc_pixels(&input_image,bmp_image_size)==NO_ERROR) printf("\nPoint2:Memoryallocated:%dbytes",_msize(input_image)); else printf("\nPoint3:Memorynotallocated"); return0; } signedcharalloc_pixels(unsignedchar**ptr,unsignedintsize) { signedcharstatus=NO_ERROR; *ptr=NULL; *ptr=(unsignedchar*)malloc(size); if(*ptr==NULL) { status=ERROR; free(*ptr);/*thislineiscompletelyredundant*/ printf("\nERROR:Memoryallocationdidnotcompletesuccessfully!"); } printf("\nPoint1:Memoryallocated:%dbytes",_msize(*ptr)); returnstatus; } Share Improvethisanswer Follow editedMay31,2016at18:18 JonathanLeffler 700k130130goldbadges861861silverbadges12311231bronzebadges answeredMay14,2010at22:34 MarkRansomMarkRansom 287k4040goldbadges379379silverbadges604604bronzebadges 6 5 WhyareyoucallingfreeinaconditionalcodeblockthatisguaranteedtohaveaNULLpointer!?!?Thefree(*ptr)willwhencalledfrommain()trytofreeinput_imagewhichwasummm,thetermevadesme...notdynamicallyallocated. – JamesMorris May14,2010at22:45 and@James:IdidwhatwassuggestedbyMarkandMatti,butthistimebothmy_mize(input_image)inmymain()and_msize(**ptr)inmyalloc_pixels(...)functionarereturningthesizeas0.Whereasifitis_msize(*ptr)(single*)returns262144.? – HaggarTheHorrible May14,2010at23:09 2 @JamesMorris,Ijustcopiedthecodethatwaspostedinthequestionandmadetheminimalnumberofchanges.Ididn'twanttogetcaughtupinadistractiontothemainpoint. – MarkRansom May15,2010at1:50 @vikramtheone,sorryIwasabitrushedanddidn'tmakethisanswerascompleteasitshouldhavebeen.I'veeditedittobemorecomplete.Ihopeyoucanseehowitisdifferentthanyouroriginalcodeandwhyitmustbethisway. – MarkRansom May15,2010at2:01 ItriedthesamethingonMSVS,butitdidnotwork.input_imageremains'badpointer'.Whatcouldbethereason? – Zeeshan Apr7,2016at9:26  |  Show1morecomment 8 Ifyouwantyourfunctiontomodifythepointeritself,you'llneedtopassitasapointertoapointer.Here'sasimplifiedexample: voidallocate_memory(char**ptr,size_tsize){ void*memory=malloc(size); if(memory==NULL){ //...errorhandling(btw,there'snoneedtocallfree()onanullpointer.Itdoesn'tdoanything.) } *ptr=(char*)memory; } intmain(){ char*data; allocate_memory(&data,16); } Share Improvethisanswer Follow editedMay14,2010at22:49 answeredMay14,2010at22:34 MattiVirkkunenMattiVirkkunen 61.4k99goldbadges119119silverbadges154154bronzebadges 13 1 It'ssafetocallfree()onanullpointer,whatisthatcommentabout? – CarlNorum May14,2010at22:37 @CarlNorum:It'ssafe,butpointless.IMO,codethatdoesn'tdoanythingonlyleadstoconfusionforpeoplewhoendupreadingitlaterandshouldbeavoided. – MattiVirkkunen May14,2010at22:38 @MattiVirkkunen:TellingpeopletonotcallfreeonaNULLpointerispointlessandmisinformation-you'recausingpeopletobecomeconfusedwhentheyseecodethatgoesagainstyouradvice. – JamesMorris May14,2010at22:43 @JamesMorris:Fine,fine...likethewordingbetternow? – MattiVirkkunen May14,2010at22:49 @Carl:I'veencountered(notverynice)Clibrariesthatcrashedifaskedtofree(NULL);soit'sgoodtoavoidanyway.(No,Idon'trememberwhich.Itwasquiteawhileago.) – DonalFellows May14,2010at22:55  |  Show8morecomments 4 Youneedtopassthepointerbyreference,notbycopy,theparameterinthefunctionalloc_pixelsrequirestheampersand&topassbackouttheaddressofthepointer-thatiscallbyreferenceinCspeak. main() { unsignedchar*input_image; unsignedintbmp_image_size=262144; if(alloc_pixels(&input_image,bmp_image_size)==NULL) printf("\nPoint2:Memoryallocated:%dbytes",_msize(input_image)); else printf("\nPoint3:Memorynotallocated"); } signedcharalloc_pixels(unsignedchar**ptr,unsignedintsize) { signedcharstatus=NO_ERROR; *ptr=NULL; *ptr=(unsignedchar*)malloc(size); if((*ptr)==NULL) { status=ERROR; /*free(ptr); printf("\nERROR:Memoryallocationdidnotcompletesuccessfully!");*/ } printf("\nPoint1:Memoryallocated:%dbytes",_msize(*ptr)); returnstatus; } Ihavecommentedoutthetwolinesfree(ptr)and"ERROR:..."withinthealloc_pixelsfunctionasthatisconfusing.Youdonotneedtofreeapointerifthememoryallocationfailed. Edit:AfterlookingatthemsdnlinksuppliedbyOP,asuggestion,thecodesampleisthesameasearlierinmyanswer....but...changetheformatspecifierto%uforthesize_ttype,intheprintf(...)callinmain(). main() { unsignedchar*input_image; unsignedintbmp_image_size=262144; if(alloc_pixels(&input_image,bmp_image_size)==NULL) printf("\nPoint2:Memoryallocated:%ubytes",_msize(input_image)); else printf("\nPoint3:Memorynotallocated"); } Share Improvethisanswer Follow editedMay15,2010at10:59 answeredMay14,2010at23:46 t0mm13bt0mm13b 33.5k88goldbadges7575silverbadges107107bronzebadges 3 IunderstandwhatwrongIwasdoing.Thereishoweveroneissuestillnotsolved.WhenImakethesechangesanduse_msize(input_image);inmymain(),the_msize(...)returnsa0.Atthesametimefor_msize(*ptr);intheotherfunction,Igetthesizeas262144.What'sgoingwronghere?Ihavenoclue. – HaggarTheHorrible May15,2010at0:30 @vikramtheone:canyoushowthefunctionprototypefor_msize(...)please?Amendyourquestiontohighlightthat... – t0mm13b May15,2010at9:07 Nevermind,itworksfinenow:)Itwasalate-latenightworkandmymindhadallbecomefuzzyandIforgottochangethemain().Iwasnotsendingtheaddressofinput_imagewhenIcallingthealloc_memory(...)inmain(). – HaggarTheHorrible May15,2010at10:56 Addacomment  |  3 Asmentionedintheotheranswers,weneedapointertothepointer.Butwhy? Weneedtopassthevaluebyapointerinordertobeabletomodifythevalue.Ifyouwanttomodifyanint,youneedtopassitbytheint*. Inthisquestion,thevaluewewanttomodifyisapointerint*(pointerchangedfromNULLtotheaddressoftheallocatedmemory),soweneedtopassapointertothepointerint**. Bydoingfollowed,pIntinsidefoo(int*)isacopyoftheargument.Whenweallocatememorytothelocalvariable,theoneinthemain()isintact. voidfoo(int*pInt) { pInt=malloc(...); } intmain() { int*pInt; foo(pInt); return0; } Soweneedapointertopointer, voidfoo(int**pInt) { *pInt=malloc(...); } intmain() { int*pInt; foo(&pInt); return0; } Share Improvethisanswer Follow editedJun1,2020at21:39 answeredJun1,2020at21:11 SongWANGSongWANG 24122silverbadges77bronzebadges Addacomment  |  2 Thisdoesnotmakesense: if(alloc_pixels(input_image,bmp_image_size)==NULL) alloc_pixelsreturnsasignedchar(ERRORorNO_ERROR)andyoucompareittoNULL(whichissupposedtobeusedforpointers). Ifyouwantinput_imagetobechanged,youneedtopassapointertoittoalloc_pixels. alloc_pixelssignaturewouldbethefollowing: signedcharalloc_pixels(unsignedchar**ptr,unsignedintsize) Youwouldcallitlikethis: alloc_pixels(&input_image,bmp_image_size); Andthememoryallocation *ptr=malloc(size); Share Improvethisanswer Follow editedMay14,2010at22:50 answeredMay14,2010at22:41 BertrandMarronBertrandMarron 20.6k88goldbadges5454silverbadges9292bronzebadges Addacomment  |  1 Inyourinitialcode,whenyouwerepassinginput_imagetothefunctionalloc_pixels,compilerwascreatingacopyofit(i.e.ptr)andstoringthevalueonthestack.Youassignthevaluereturnedbymalloctoptr.Thisvalueislostoncethefunctionreturnstomainandthestackunwinds.So,thememoryisstillallocatedonheapbutthememorylocationwasneverstoredin(orassignedto)input_image,hencetheissue. Youcanchangethesignatureofthefunctionalloc_pixelswhichwouldbesimplertounderstand,andyouwon'trequiretheadditional'status'variableaswell. unsignedchar*alloc_pixels(unsignedintsize) { unsignedchar*ptr=NULL; ptr=(unsignedchar*)malloc(size); if(ptr!=NULL) printf("\nPoint1:Memoryallocated:%dbytes",_msize(ptr)); returnptr; } Youcancalltheabovefunctioninmain: intmain() { unsignedchar*input_image; unsignedintbmp_image_size=262144; if((input_image=alloc_pixels(bmp_image_size))==NULL) printf("\nPoint3:Memorynotallocated"); else printf("\nPoint2:Memoryallocated:%dbytes",_msize(input_image)); return0; } Share Improvethisanswer Follow answeredMay15,2010at6:42 juventusjuventus 5211bronzebadge Addacomment  |  1 Parameters'assignmentwillworkonlyifyousetthevaluetoitsaddress. Thereare2pointsthatyoushouldknowbeforeyouattempttosolvethisproblem: 1.CFunction:Alltheparametersyoupassedtothefunctionwillbeacopyinthefunction. Thatmeanseveryassignmentthatyou'vemadeinthefunctionwillnotaffectthevariablesoutsidethefunction,you'reworkingonthecopyactually: inti=1; fun(i); printf("%d\n",i); //nomatterwhatkindofchangesyou'vemadetoiinfun,i'svaluewillbe1 So,ifyouwanttochangeiinthefunction,youneedtoknowthedifferencebetweenthethinganditscopy: Thecopysharedthevaluewiththething,butnottheaddress. Andthat'stheironlydifference. Sotheonlywaytochangeiinthefunctionisusingtheaddressofi. Forexample,there'sanewfunctionfun_addr: voidfun_addr(int*i){ *i=some_value; } Inthisway,youcouldchangei'svalue. malloc: Thekeypointinthefun_addrfunctionis,you'vepassedaaddresstothefunction.Andyoucouldchangethevaluestoredinthataddress. Whatwillmallocdo? mallocwillallocateanewmemoryspace,andreturnthepointerpointedtothataddressback. Lookatthisinstruction: int*array=(int*)malloc(sizeof(int)*SIZE); Whatyouaredoingisletarray'svalueequalstotheaddressreturnedbymalloc. See?Thisisthesamequestion,permanentlyassigningvaluetotheparameterpassedtothefunction.Atthispoint,thevalueisaddress. Now,assigntheaddress(returnedbymalloc)totheaddress(storestheoldaddress). Sothecodeshouldbe: voidfun_addr_addr(int**p){ *p=(int*)malloc(sizeof(int)*SIZE); } Thisonewillwork. Share Improvethisanswer Follow answeredSep21,2014at11:10 VELVETDETHVELVETDETH 30411silverbadge88bronzebadges Addacomment  |  1 TheonlywayIcouldgetpointertoapointersolutiontoworkforasimilarproblemIwashavingforthisfunction BOOLOpenBitmap2(LPCTSTRpszFileName,char**pszBMPFile) Wasbyassigningatemporarypointertostoretheaddress char*BMPFile; {BMPFile=(char*)GlobalAlloc(GPTR,dwFileSize+1);//allocatestorageusingGlobalAlloc+1fornulltermstring thenreassigningit {*pszBMPFile=BMPFile;return(0);}//Error=False Anycommentonwhyusing"*pszBMPFile"directlywithGlobalAllocdidn'tworkwouldbeappreciated. Iansweredmyownquestion.Iforgottocarrythe"*"throughwithpszBMPFileintheotherlinesofcode.Goodlessonsfromallthecontributors.Manythanks. Share Improvethisanswer Follow editedNov25,2017at23:18 answeredNov25,2017at11:50 PeterSPeterS 1122bronzebadges 0 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?Browseotherquestionstaggedcfunctionpointersmallocoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool AskWizardTestResultsandNextSteps Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Trending:Anewanswersortingoption Linked 6 dynamicmemorycreatedinsideafunction 3 Usingreallocinsideafunction 2 Pointernotassigned 0 VisualC++PointerScope 0 HowcanIupdateapointerargumentinsideafunction? 0 isthereawayforReallocinfunctionscorrectly? 0 C-Arrayinitializationinsidefunction 0 AmendinganarraybyreferenceusingpointersinC 0 AfterresizingstructandmovingPointer,Pointerdoesnotshowtotheaddressheshouldpointat -1 Whycan'tIaccesstothelocatedmemory? Seemorelinkedquestions Related 2056 What'sthedifferencebetweenamethodandafunction? 7439 varfunctionName=function(){}vsfunctionfunctionName(){} 2676 DoIcasttheresultofmalloc? 614 WhatREALLYhappenswhenyoudon'tfreeaftermallocbeforeprogramtermination? 1421 HowdofunctionpointersinCwork? 2574 SetadefaultparametervalueforaJavaScriptfunction 877 Differencebetweenmallocandcalloc? 1397 Whatdoestheexclamationmarkdobeforethefunction? 2 Understandingmalloc HotNetworkQuestions CanVresolvetoiii? Dosymmetricalairfoilsgenerateinduceddrag? Uglyshadowglitch /var/loghasreached56.6GB.Howtocleanitandmakemorespace? WhydidoldconsoleshavespecialRAMdedicatedforaspecifictask? HowtotransferanNFTfromacontractaddresstoawalletaddress Doestheemailsizelimitincludethesizeofthebody? Isitacceptabletoincludeinformationinaposterthatwasn'tinthepublication? Reduceforadifficultcase Howtallarethemushrooms? Wouldasolarsystemwithfourearthsdirectlyoppositetoeachotherhavedifferentflora? ResourcesonthestationarySchrodingerequationwiththesolitonpotential UVUnwrapontocylinder Can"due"meaning"owed"beusedwithout"to"inAmE?e.g."therecognitionwhichwasdueher" ConfusionwithDopplerEffectproblem Upperboundforrandomcorrelation HowtomakeQuantityrememberinterpretation? Whatdoyoucallthepointypartsofatextbubblethat'snotthetail? Firsttimeflyingwithcarryononly.CanIcarrydoubleedgedrazorbladeswithme? IterativeSmallestComplement Formallanguagerewriterules:strangenotation WhatcanIdoifaflightdelaymakesmemissthetransferfromtheairport? SymmetricalChessPositionWithNoLegalMoves SeparationoftheChurchandStateinHinduism morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?