making your own malloc function in C - Stack Overflow

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

or call the standard malloc for a large block of continuous memory on startup and write yr own malloc type function to divide that down. In 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 makingyourownmallocfunctioninC AskQuestion Asked 9years,6monthsago Modified 1year,9monthsago Viewed 37ktimes 6 4 Ineedyourhelpinthis.IhaveanaverageknowledgeofCandhereistheproblem.Iamabouttousesomebenchmarkstotestsomecomputerarchitecturestuff(branchmisses,cachemisses)onanewprocessor.ThethingaboutitisthatbenchmarksareinCbutImustnotincludeanylibrarycalls.Forexample,IcannotusemallocbecauseIamgettingtheerror "undefinedreferencetomalloc" evenifIhaveincludedthelibrary.SoIhavetowritemyownmalloc.Idonotwantittobesuperefficient-justdothebasics.AsIamthinkingitImusthaveanaddressinmemoryandeverytimeamallochappens,Ireturnapointertothataddressandincrementthecounterbythatsize.MallochappenstwiceinmyprogramsoIdonotevenneedlargememory. Canyouhelpmeonthat?IhavedesignedaVeriloganddonothavesomuchexperienceinC. Ihaveseenpreviousanswersbutallseemtoocomplicatedforme.Besides,IdonothaveaccesstoK-Rbook. Cheers! EDIT:maybethiscanhelpyoumore: Iamnotusinggccbutthesde-gcccompiler.Doesitmakeanydifference?Maybethat'swhyIamgettinganundefinedreferencetomalloc? EDIT2: IamtestingaMIPSarchitecture: Ihaveincluded: #include andtheerrorsare: undefinedreferencetomalloc relocationtruncatedtofit:R_MIPS_26againstmalloc andthecompilercommandid: test.o:test.ccap.h sde-gcc-c-otest.stest.c-EB-march=mips64-mabi=64-G-O-ggdb-O2-S sde-as-otest.otest.sEB-march=mips64-mabi=64-G-O-ggdb as_objects:=test.oinit.o EDIT3: ok,Iusedimplementationaboveanditrunswithoutanyproblems.Theproblemisthatwhendoingembeddedprogramming,youjusthavetodefineeverythingyouareusingsoIdefinedmyownmalloc.sde-gccdidn'trecognizethemallocfunction. cmalloc Share Improvethisquestion Follow editedApr13,2018at8:17 Saheb 1,27433goldbadges1313silverbadges3030bronzebadges askedDec7,2012at14:09 ghostriderghostrider 5,0611414goldbadges6868silverbadges114114bronzebadges 23 possibleduplicateofCodeformallocandfree – ŠimonTóth Dec7,2012at14:12 Ifyoureallywanttoimplementyourownmalloc,havealookatthesyscallssbrk()andbrk()thatwillhelpyoumodifythesizeoftheheap. – Intrepidd Dec7,2012at14:12 1 @Mike:Youkeepaskingaboutcompilation,buttheundefinedreferencetomallocappearstobealinkerror.Thisisacommoninembeddedprogramming.Addtothatthattheaskerisbenchmarkinglow-levelcomputerarchitecturefeaturesandnotwritingauser-levelapplication,anditseemslikelytheyareworkinginanembeddedenvironmentwheremallocmaybeunavailable,astheystated.Soyourquestionsaboutcompilingmaybeoffthemark.Ifyouwanttopursuethis,youshouldestablishfirstwhethermallocisactuallyavailableinthelibraries(nottheheaderfiles). – EricPostpischil Dec7,2012at15:11 1 @ghostriderThat'sstillnottherelevantpart.Youareshowingcompilationcommands,butweneedtoseethelinkercommand. – ŠimonTóth Dec7,2012at15:25 1 @Let_Me_Be:Objectingtoclarifyingtherequirementsisantitheticaltoengineering.Thereisnoreasonnottoensuretheproblemisdefinedproperly.OPhasstated:“Imustnotincludeanylibrarycalls”and“IwanttoknowifIcanwriteitwithoutanysyscalls.”Theyhaveclearlystatedtheirdesire.Ifyouwanttoansweradifferentquestion,thenyououghttoatleastconfirmthesituation. – EricPostpischil Dec7,2012at15:43  |  Show18morecomments 4Answers 4 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 22 Thisisaverysimpleapproach,whichmaygetyoupastyour2mallocs: staticunsignedcharour_memory[1024*1024];//reserve1MBformalloc staticsize_tnext_index=0; void*malloc(size_tsz) { void*mem; if(sizeofour_memory-next_index=MAX_ALOCATION_ALLOWED) { returnNULL; } for(index=0;index=size) { initial_flag=TRUE; break; } else { gap=metadata_info[index+1].address-(metadata_info[index].address+metadata_info[index].size);/*CheckGapBetweentwoallocatedmemory(Case2)*/ if(gap>=size) { flag=TRUE; break; } } } } if(flag==TRUE)/*GetIndexforallocatingmemoryforcase2*/ { heap_index=((metadata_info[index].address+metadata_info[index].size)-g_heap_base_address); for(j=MAX_ALOCATION_ALLOWED-1;j>index+1;j--) { memcpy(&metadata_info[j],&metadata_info[j-1],sizeof(malloc_info_t)); } } elseif(initial_flag==TRUE)/*GetIndexforallocatingmemoryforcase3*/ { heap_index=0; for(j=MAX_ALOCATION_ALLOWED-1;j>index+1;j--) { memcpy(&metadata_info[j],&metadata_info[j-1],sizeof(malloc_info_t)); } } else/*GetIndexforallocatingmemoryforcase1*/ { if(g_allocted_number!=0) { heap_index=((metadata_info[index-1].address+metadata_info[index-1].size)-g_heap_base_address); } else/*0thLocationofMetadataforFirsttimeallocation*/ heap_index=0; } address=&our_memory[heap_index]; metadata_info[index].address=g_heap_base_address+heap_index; metadata_info[index].size=size; g_allocted_number+=1; returnaddress; } NowCodeforFree voidmy_free(intaddress) { inti=0; intcopy_meta_data=FALSE; for(i=0;ic`beshortenedinJavascript? WhywouldanyonebuyaPonyoveraMule? Rigorousbooksonbasiccomputabilitytheory SolvingaSimple'SumandProduct'Problem DoesthereexistaLatinsquareoforder9forwhichits9brokendiagonalsand9brokenantidiagonalsaretransversals? Palindromeanimationpausingatbeginningandend Iboughtmyfirstroadbike,andithurtsmybackandhands Howwouldyoustandardizeon-callexpectationsacrosssoftwareteamswhenthey'vedivergedatthesamesalarylevel? Isthereageneralwaytoparametrize2-qubitunitaries? Whatisthenameofthecategoryforthevibrationsthatthetonguedoesinlinguistics? Isitacceptabletoincludeinformationinaposterthatwasn'tinthepublication? Whatdoes"CATsthreeandfour"mean? WhatarethemainargumentsusedbyChristianpro-liferstojustifytheirstanceagainstabortion? BivariateHermitePolynomials morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?