0% found this document useful (0 votes)
117 views

Dynamic Memory Allocation in C Using Malloc, Calloc, Free and Realloc

Uploaded by

Karthikeya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

Dynamic Memory Allocation in C Using Malloc, Calloc, Free and Realloc

Uploaded by

Karthikeya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Courses Tutorials Jobs Practice Sign In

Data Structures Algorithms Interview Preparation Topic-wise Practice C++ Java Python Competitive Programming Machine Learning HTML SDE Sheet Puzzles GFG School Projects

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


realloc()
Difficulty Level :
Easy ● Last Updated :
09 Dec, 2021

Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a

collection of items stored at contiguous memor y locations. 

A s it can be seen that the length (size) of the array above made is 9. But what if there is a requirement to change this length (size). For

Example, 

If there is a situation where only 5 element s are needed to be entered in this array. In this case, the remaining 4 indices are just wasting

memor y in this array. So there is a requirement to lessen the length (size) of the array from 9 to 5.

Take another situation. In this, there is an array of 9 element s with all 9 indices filled. But there is a need to enter 3 more element s in

this array. In this case, 3 indices more are required. So the length (size) of the array needs to be changed from 9 to 12.

This procedure is referred to as Dynamic Memor y Allocation in C.

Therefore, C Dynamic Memor y Allocation can be defined as a procedure in which the size of a data structure (like Array) is changed

during the runtime.

C provides some functions to achieve these task s. There are 4 librar y functions provided by C defined under <stdlib.h> header file to

facilitate dynamic memor y allocation in C programming. They are:  WHAT'S NEW


1. malloc()

2. calloc()
Geek-O-Lympics 2022
3. free()

4. realloc() View Details

Let ’s look at each of them in greater detail. Complete Interview Preparation- Self Paced
Course
C malloc() method
View Details

The “malloc ” or “memor y allocation” method in C is used to dynamically allocate a single large block of memor y with the specified size. Data Structures & Algorithms- Self Paced
It returns a pointer of t ype void which can be cast into a pointer of any form. It doesn’t Initialize memor y at execution time so that it has Course
initialized each block with the default garbage value initially. 
View Details
Syntax : 

ptr = (cast-type*) malloc(byte-size)

For Example:

ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes of memor y. And, the pointer ptr holds the address of the first

byte in the allocated memor y.

MOST POPULAR IN C LANGUAGE


If space is insuf ficient, allocation fails and returns a NULL pointer.

Example :  Substring in C++

C Function Pointer in C
#include <stdio.h>
#include <stdlib.h> Different Methods to Reverse a String in
 
int main() C++
{
 
    // This pointer will hold the std::string class in C++
    // base address of the block created
    int* ptr;
    int n, i;
 
Unordered Sets in C++ Standard
    // Get the number of elements for the array
    printf("Enter number of elements:");
Template Library
    scanf("%d",&n);
    printf("Entered number of elements: %d\n", n);
 
    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");
 
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
    }
 
    return 0;
}

Output : 
MORE RELATED ARTICLES IN C
Enter number of elements: 5
LANGUAGE
Memory successfully allocated using malloc.

The elements of the array are: 1, 2, 3, 4, 5, Enumeration (or enum) in C


 
C Language Introduction

Power Function in C/C++


C calloc() method

1. “calloc ” or “contiguous allocation” method in C is used to dynamically allocate the specified number of block s of memor y of the

specified t ype. it is ver y much similar to malloc() but has two dif ferent point s and these are: INT_MAX and INT_MIN in C/C++ and
Applications
2. It initializes each block with a default value ‘0’.

3. It has two parameters or argument s as compare to malloc().

Syntax :  Operators in C / C++


ptr = (cast-type*)calloc(n, element-size);

here, n is the no. of elements and element-size is the size of each element.

For Example : 

ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous space in memor y for 25 element s each with the size of the float.

If space is insuf ficient, allocation fails and returns a NULL pointer.

Example :

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i;
 
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
 
    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by calloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");
 
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
    }
 
    return 0;
}

Output : 

Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

C free() method

“free” method in C is used to dynamically de-allocate the memor y. The memor y allocated using functions malloc() and calloc() is not de-

allocated on their own. Hence the free() method is used, whenever the dynamic memor y allocation takes place. It helps to reduce

wastage of memor y by freeing it.

Syntax : 

free(ptr);

Example :

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int *ptr, *ptr1;
    int n, i;
 
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
 
    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
 
    // Dynamically allocate memory using calloc()
    ptr1 = (int*)calloc(n, sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL || ptr1 == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");
 
        // Free the memory
        free(ptr);
        printf("Malloc Memory successfully freed.\n");
 
        // Memory has been successfully allocated
        printf("\nMemory successfully allocated using calloc.\n");
 
        // Free the memory
        free(ptr1);
        printf("Calloc Memory successfully freed.\n");
    }
 
    return 0;
}

Output : 

Enter number of elements: 5

Memory successfully allocated using malloc.

Malloc Memory successfully freed.

Memory successfully allocated using calloc.

Calloc Memory successfully freed.

C realloc() method

“realloc ” or “re-allocation” method in C is used to dynamically change the memor y allocation of a previously allocated memor y. In other

words, if the memor y previously allocated with the help of malloc or calloc is insuf ficient, realloc can be used to dynamically re-allocate

memor y. re-allocation of memor y maintains the already present value and new block s will be initialized with the default garbage value.

Syntax : 

ptr = realloc(ptr, newSize);

where ptr is reallocated with new size 'newSize'.

If space is insuf ficient, allocation fails and returns a NULL pointer.

Example :

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i;
 
    // Get the number of elements for the array
    n = 5;
    printf("Enter number of elements: %d\n", n);
 
    // Dynamically allocate memory using calloc()
    ptr = (int*)calloc(n, sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using calloc.\n");
 
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
 
        // Get the new size for the array
        n = 10;
        printf("\n\nEnter the new size of the array: %d\n", n);
 
        // Dynamically re-allocate memory using realloc()
        ptr = realloc(ptr, n * sizeof(int));
 
        // Memory has been successfully allocated
        printf("Memory successfully re-allocated using realloc.\n");
 
        // Get the new elements of the array
        for (i = 5; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
 
        free(ptr);
    }
 
    return 0;
}

Output : 

Enter number of elements: 5

Memory successfully allocated using calloc.

The elements of the array are: 1, 2, 3, 4, 5,

Enter the new size of the array: 10

Memory successfully re-allocated using realloc.

The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

One another example for realloc() method is:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int index = 0, i = 0, n,
        *marks; // this marks pointer hold the base address
                // of  the block created
    int ans;
    marks = (int*)malloc(sizeof(
        int)); // dynamically allocate memory using malloc
    // check if the memory is successfully allocated by
    // malloc or not?
    if (marks == NULL) {
        printf("memory cannot be allocated");
    }
    else {
        // memory has successfully allocated
        printf("Memory has been successfully allocated by "
               "using malloc\n");
        printf("\n marks = %pc\n",
               marks); // print the base or beginning
                       // address of allocated memory
        do {
            printf("\n Enter Marks\n");
            scanf("%d", &marks[index]); // Get the marks
            printf("would you like to add more(1/0): ");
            scanf("%d", &ans);
 
            if (ans == 1) {
                index++;
                marks = (int*)realloc(
                    marks,
                    (index + 1)
                        * sizeof(
                            int)); // Dynamically reallocate
                                   // memory by using realloc
                // check if the memory is successfully
                // allocated by realloc or not?
                if (marks == NULL) {
                    printf("memory cannot be allocated");
                }
                else {
                    printf("Memory has been successfully "
                           "reallocated using realloc:\n");
                    printf(
                        "\n base address of marks are:%pc",
                        marks); ////print the base or
                                ///beginning address of
                                ///allocated memory
                }
            }
        } while (ans == 1);
        // print the marks of the students
        for (i = 0; i <= index; i++) {
            printf("marks of students %d are: %d\n ", i,
                   marks[i]);
        }
        free(marks);
    }
    return 0;
}

Output :

Like 473

Previous Next

Difference Between malloc() and calloc() with How to dynamically allocate a 2D array in C?
Examples

RECOMMENDED ARTICLES Page : 1 2 3

Difference Between malloc() and calloc() with Static and Dynamic Memory Allocation in C
01 05
Examples 21, Apr 21

27, Feb 10

what happens when you don't free memory after new vs malloc() and free() vs delete in C++
02
using malloc() 06 20, May 20

20, Jun 20

Program to find largest element in an array using


03
Dynamic Memory Allocation C | Dynamic Memory Allocation | Question 1
07 09, Feb 13
02, Sep 20

Difference between Static and Dynamic Memory


04
Allocation in C C | Dynamic Memory Allocation | Question 2
18, Aug 20
08 09, Feb 13

Article Contributed B y : Vote for dif ficult y

Current difficulty :
Easy

RishabhPrabhu
@RishabhPrabhu Easy Normal Medium Hard Expert

Improved By : newcollegetalent, Navfal, menariyanarayanlal, AnujMehla, khushboogoyal499


Article Tags : C Basics, Dynamic Memory Allocation, C Language

Improve Article Report Issue

Writing code in comment?


Please use ide.geeksforgeeks.org,
generate link and share the link here.

Load Comments

Company Learn News Languages Web Development Contribute


A-143, 9th Floor, Sovereign Corporate Tower, About Us Algorithms Python Web Tutorials Write an Article
Sector-136, Noida, Uttar Pradesh - 201305 Top News
feedback@geeksforgeeks.org Careers Data Structures Java Django Tutorial Improve an Article
Technology
In Media SDE Cheat Sheet CPP HTML Pick Topics to Write
Work & Career
Contact Us Machine learning Golang JavaScript Write Interview Experience
Business
Privacy Policy CS Subjects C# Bootstrap Internships
Finance
Copyright Policy Video Tutorials SQL ReactJS Video Internship
Lifestyle
Courses Kotlin NodeJS
Knowledge

@geeksforgeeks
, Some rights reserved

You might also like