Dynamic Memory Allocation in C using malloc(), calloc(), free ...

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

C malloc() method ... The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesUnderstanding“extern”keywordinCStorageClassesinCStaticVariablesinCMemoryLayoutofCProgramsHowtodeallocatememorywithoutusingfree()inC?DifferenceBetweenmalloc()andcalloc()withExamplesDynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()Howtodynamicallyallocatea2DarrayinC?Howtopassa2DarrayasaparameterinC?MultidimensionalArraysinC/C++2DVectorInC++WithUserDefinedSizeVectorofVectorsinC++STLwithExamplesVectorinC++STLTheC++StandardTemplateLibrary(STL)SortinC++StandardTemplateLibrary(STL)WhatarethedefaultvaluesofstaticvariablesinC?Understanding“volatile”qualifierinC|Set2(Examples)ConstQualifierinCInitializationofstaticvariablesinCUnderstanding“register”keywordinCArraysinC/C++std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++WhatisMemoryLeak?Howcanweavoid?ConvertingStringstoNumbersinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++Understanding“extern”keywordinCStorageClassesinCStaticVariablesinCMemoryLayoutofCProgramsHowtodeallocatememorywithoutusingfree()inC?DifferenceBetweenmalloc()andcalloc()withExamplesDynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()Howtodynamicallyallocatea2DarrayinC?Howtopassa2DarrayasaparameterinC?MultidimensionalArraysinC/C++2DVectorInC++WithUserDefinedSizeVectorofVectorsinC++STLwithExamplesVectorinC++STLTheC++StandardTemplateLibrary(STL)SortinC++StandardTemplateLibrary(STL)WhatarethedefaultvaluesofstaticvariablesinC?Understanding“volatile”qualifierinC|Set2(Examples)ConstQualifierinCInitializationofstaticvariablesinCUnderstanding“register”keywordinCArraysinC/C++std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++WhatisMemoryLeak?Howcanweavoid?ConvertingStringstoNumbersinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()ViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 09Dec,2021SinceCisastructuredlanguage,ithassomefixedrulesforprogramming.Oneofthemincludeschangingthesizeofanarray.Anarrayisacollectionofitemsstoredatcontiguousmemorylocations. Asitcanbeseenthatthelength(size)ofthearrayabovemadeis9.Butwhatifthereisarequirementtochangethislength(size).ForExample, Ifthereisasituationwhereonly5elementsareneededtobeenteredinthisarray.Inthiscase,theremaining4indicesarejustwastingmemoryinthisarray.Sothereisarequirementtolessenthelength(size)ofthearrayfrom9to5.Takeanothersituation.Inthis,thereisanarrayof9elementswithall9indicesfilled.Butthereisaneedtoenter3moreelementsinthisarray.Inthiscase,3indicesmorearerequired.Sothelength(size)ofthearrayneedstobechangedfrom9to12.ThisprocedureisreferredtoasDynamicMemoryAllocationinC.Therefore,CDynamicMemoryAllocationcanbedefinedasaprocedureinwhichthesizeofadatastructure(likeArray)ischangedduringtheruntime.Cprovidessomefunctionstoachievethesetasks.Thereare4libraryfunctionsprovidedbyCdefinedunderheaderfiletofacilitatedynamicmemoryallocationinCprogramming.Theyare: malloc()calloc()free()realloc()Let’slookateachofthemingreaterdetail.Cmalloc()methodThe“malloc”or“memoryallocation”methodinCisusedtodynamicallyallocateasinglelargeblockofmemorywiththespecifiedsize.Itreturnsapointeroftypevoidwhichcanbecastintoapointerofanyform.Itdoesn’tInitializememoryatexecutiontimesothatithasinitializedeachblockwiththedefaultgarbagevalueinitially. Syntax: ptr=(cast-type*)malloc(byte-size) ForExample:ptr=(int*)malloc(100*sizeof(int));Sincethesizeofintis4bytes,thisstatementwillallocate400bytesofmemory.And,thepointerptrholdstheaddressofthefirstbyteintheallocatedmemory. Ifspaceisinsufficient,allocationfailsandreturnsaNULLpointer.Example: C#include#include intmain(){     //Thispointerwillholdthe    //baseaddressoftheblockcreated    int*ptr;    intn,i;     //Getthenumberofelementsforthearray    printf("Enternumberofelements:");    scanf("%d",&n);    printf("Enterednumberofelements:%d\n",n);     //Dynamicallyallocatememoryusingmalloc()    ptr=(int*)malloc(n*sizeof(int));     //Checkifthememoryhasbeensuccessfully    //allocatedbymallocornot    if(ptr==NULL){        printf("Memorynotallocated.\n");        exit(0);    }    else{         //Memoryhasbeensuccessfullyallocated        printf("Memorysuccessfullyallocatedusingmalloc.\n");         //Gettheelementsofthearray        for(i=0;i#include intmain(){     //Thispointerwillholdthe    //baseaddressoftheblockcreated    int*ptr;    intn,i;     //Getthenumberofelementsforthearray    n=5;    printf("Enternumberofelements:%d\n",n);     //Dynamicallyallocatememoryusingcalloc()    ptr=(int*)calloc(n,sizeof(int));     //Checkifthememoryhasbeensuccessfully    //allocatedbycallocornot    if(ptr==NULL){        printf("Memorynotallocated.\n");        exit(0);    }    else{         //Memoryhasbeensuccessfullyallocated        printf("Memorysuccessfullyallocatedusingcalloc.\n");         //Gettheelementsofthearray        for(i=0;i#include intmain(){     //Thispointerwillholdthe    //baseaddressoftheblockcreated    int*ptr,*ptr1;    intn,i;     //Getthenumberofelementsforthearray    n=5;    printf("Enternumberofelements:%d\n",n);     //Dynamicallyallocatememoryusingmalloc()    ptr=(int*)malloc(n*sizeof(int));     //Dynamicallyallocatememoryusingcalloc()    ptr1=(int*)calloc(n,sizeof(int));     //Checkifthememoryhasbeensuccessfully    //allocatedbymallocornot    if(ptr==NULL||ptr1==NULL){        printf("Memorynotallocated.\n");        exit(0);    }    else{         //Memoryhasbeensuccessfullyallocated        printf("Memorysuccessfullyallocatedusingmalloc.\n");         //Freethememory        free(ptr);        printf("MallocMemorysuccessfullyfreed.\n");         //Memoryhasbeensuccessfullyallocated        printf("\nMemorysuccessfullyallocatedusingcalloc.\n");         //Freethememory        free(ptr1);        printf("CallocMemorysuccessfullyfreed.\n");    }     return0;}Output: Enternumberofelements:5 Memorysuccessfullyallocatedusingmalloc. MallocMemorysuccessfullyfreed. Memorysuccessfullyallocatedusingcalloc. CallocMemorysuccessfullyfreed. Crealloc()method“realloc”or“re-allocation”methodinCisusedtodynamicallychangethememoryallocationofapreviouslyallocatedmemory.Inotherwords,ifthememorypreviouslyallocatedwiththehelpofmallocorcallocisinsufficient,realloccanbeusedtodynamicallyre-allocatememory.re-allocationofmemorymaintainsthealreadypresentvalueandnewblockswillbeinitializedwiththedefaultgarbagevalue.Syntax: ptr=realloc(ptr,newSize); whereptrisreallocatedwithnewsize'newSize'.Ifspaceisinsufficient,allocationfailsandreturnsaNULLpointer.Example:C#include#include intmain(){     //Thispointerwillholdthe    //baseaddressoftheblockcreated    int*ptr;    intn,i;     //Getthenumberofelementsforthearray    n=5;    printf("Enternumberofelements:%d\n",n);     //Dynamicallyallocatememoryusingcalloc()    ptr=(int*)calloc(n,sizeof(int));     //Checkifthememoryhasbeensuccessfully    //allocatedbymallocornot    if(ptr==NULL){        printf("Memorynotallocated.\n");        exit(0);    }    else{         //Memoryhasbeensuccessfullyallocated        printf("Memorysuccessfullyallocatedusingcalloc.\n");         //Gettheelementsofthearray        for(i=0;i#includeintmain(){    intindex=0,i=0,n,        *marks;//thismarkspointerholdthebaseaddress                //of theblockcreated    intans;    marks=(int*)malloc(sizeof(        int));//dynamicallyallocatememoryusingmalloc    //checkifthememoryissuccessfullyallocatedby    //mallocornot?    if(marks==NULL){        printf("memorycannotbeallocated");    }    else{        //memoryhassuccessfullyallocated        printf("Memoryhasbeensuccessfullyallocatedby"               "usingmalloc\n");        printf("\nmarks=%pc\n",               marks);//printthebaseorbeginning                       //addressofallocatedmemory        do{            printf("\nEnterMarks\n");            scanf("%d",&marks[index]);//Getthemarks            printf("wouldyouliketoaddmore(1/0):");            scanf("%d",&ans);             if(ans==1){                index++;                marks=(int*)realloc(                    marks,                    (index+1)                        *sizeof(                            int));//Dynamicallyreallocate                                   //memorybyusingrealloc                //checkifthememoryissuccessfully                //allocatedbyreallocornot?                if(marks==NULL){                    printf("memorycannotbeallocated");                }                else{                    printf("Memoryhasbeensuccessfully"                           "reallocatedusingrealloc:\n");                    printf(                        "\nbaseaddressofmarksare:%pc",                        marks);////printthebaseor                                ///beginningaddressof                                ///allocatedmemory                }            }        }while(ans==1);        //printthemarksofthestudents        for(i=0;i<=index;i++){            printf("marksofstudents%dare:%d\n",i,                   marks[i]);        }        free(marks);    }    return0;}Output:MyPersonalNotes arrow_drop_upSave LikePreviousDifferenceBetweenmalloc()andcalloc()withExamplesNext Howtodynamicallyallocatea2DarrayinC?RecommendedArticlesPage:27,Feb1020,Jun2002,Sep2018,Aug2021,Apr2120,May2009,Feb1309,Feb1309,Feb1305,Mar1331,Jul1331,Jul1303,Sep1303,Sep1319,Dec1026,Sep1702,Feb1421,Dec1125,Aug1022,Feb1608,Mar2101,Jul1107,Sep1021,Oct20ArticleContributedBy:RishabhPrabhu@RishabhPrabhuVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:newcollegetalentNavfalmenariyanarayanlalAnujMehlakhushboogoyal499ArticleTags:CBasicsDynamicMemoryAllocationCLanguageReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinCLanguageSubstringinC++std::stringclassinC++DifferentMethodstoReverseaStringinC++PowerFunctioninC/C++FunctionPointerinCMorerelatedarticlesinCLanguageEnumeration(orenum)inCCommandlineargumentsinC/C++StructuresinCCLanguageIntroductionExceptionHandlinginC++ImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?