Open In App

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

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 memory locations. 

arrays

As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, 

  • If there is a situation where only 5 elements are needed to be entered in this array. In this case, the remaining 4 indices are just wasting memory 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 elements with all 9 indices filled. But there is a need to enter 3 more elements 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 Memory Allocation in C.
Therefore, C Dynamic Memory 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 tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: 

  1. malloc()
  2. calloc()
  3. free()
  4. realloc()


Let’s look at each of them in greater detail.

C malloc() method

The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default garbage value initially. 

Syntax of malloc() in C

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 memory. And, the pointer ptr holds the address of the first byte in the allocated memory.

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

Example of malloc() in C

C
#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
    printf("Enter number of elements:");
    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

Enter number of elements:7
Entered number of elements: 7
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7,

C calloc() method

  1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. it is very much similar to malloc() but has two different points and these are:
  2. It initializes each block with a default value ‘0’.
  3. It has two parameters or arguments as compare to malloc().

Syntax of calloc() in 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 memory for 25 elements each with the size of the float.
 


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

Example of calloc() in C

C
#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 memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.

Syntax of free() in C

free(ptr);

Example of free() in C

C
#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 memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. re-allocation of memory maintains the already present value and new blocks will be initialized with the default garbage value.

Syntax of realloc() in C

ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.

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

Example of realloc() in C

C
#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 = (int*)realloc(ptr, n * sizeof(int));
      
          if (ptr == NULL) {
          printf("Reallocation Failed\n");
          exit(0);
        }

        // 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:

C
#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

output of the above program




Previous Article
Next Article

Similar Reads

Difference Between malloc() and calloc() with Examples
The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the memory is allocated during runtime (execution of the program) from the heap segment. Initializationmalloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn't initialize t
3 min read
what happens when you don't free memory after using malloc()
Pre-requisite: Dynamic memory allocation in CThe "malloc" or "memory allocation" method is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default garbage value.Syntax: ptr = (cast-type*) malloc(byte-
3 min read
Difference between Static and Dynamic Memory Allocation in C
Memory Allocation: Memory allocation is a process by which computer programs and services are assigned with physical or virtual memory space. The memory allocation is done either before or at the time of program execution. There are two types of memory allocations: Compile-time or Static Memory AllocationRun-time or Dynamic Memory AllocationStatic
3 min read
C | Dynamic Memory Allocation | Question 1
The most appropriate matching for the following pairs (GATE CS 2000) X: m=malloc(5); m= NULL;        1: using dangling pointers Y: free(n); n-&gt;value=5;         2: using uninitialized pointers Z: char *p; *p = ’a’;           3. lost memory is: (A) X—1 Y—3 Z-2 (B) (X—2 Y—1 Z-3 (C) X—3 Y—2 Z-1 (D) X—3 Y—1 Z-2 Answer: (D) Explanation: X -&gt; A poin
1 min read
C | Dynamic Memory Allocation | Question 2
Consider the following three C functions : [PI] int * g (void) { int x= 10; return (&amp;x); } [P2] int * g (void) { int * px; *px= 10; return px; } [P3] int *g (void) { int *px; px = (int *) malloc (sizeof(int)); *px= 10; return px; } Which of the above three functions are likely to cause problems with pointers? (GATE 2001) (A) Only P3 (B) Only P1
1 min read
C | Dynamic Memory Allocation | Question 3
Output? C/C++ Code # include # include void fun(int *a) { a = (int*)malloc(sizeof(int)); } int main() { int *p; fun(p); *p = 6; printf(\"%d",*p); return(0); } (A) May not work (B) Works and prints 6 Answer: (A)Explanation: The program is not valid. Try replacing “int *p;” with “int *p = NULL;” and it will try to dereference a null pointer. This is
1 min read
C | Dynamic Memory Allocation | Question 8
Which of the following is/are true (A) calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has uninitialized data. (B) malloc() and memset() can be used to get the same effect as calloc(). (C) calloc() takes two arguments, but malloc takes only 1 argument. (D) Both malloc() and call
1 min read
C | Dynamic Memory Allocation | Question 5
What is the return type of malloc() or calloc() (A) void * (B) Pointer of allocated memory type (C) void ** (D) int * Answer: (A) Explanation: malloc() and calloc() return void *. We may get warning in C if we don't type cast the return type to appropriate pointer. Quiz of this Question
1 min read
C | Dynamic Memory Allocation | Question 6
Which of the following is true? (A) "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m * n); (B) "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m * n); memset(ptr, 0, m * n); (C) "ptr = calloc(m, n)" is equivalent to following ptr = malloc(m); memset(ptr, 0, m); (D) "ptr = calloc(m, n)" is equivalent to following ptr = mal
1 min read
C | Dynamic Memory Allocation | Question 7
What is the problem with following code? #include&lt;stdio.h&gt; int main() { int *p = (int *)malloc(sizeof(int)); p = NULL; free(p); } (A) Compiler Error: free can't be applied on NULL pointer (B) Memory Leak (C) Dangling Pointer (D) The program may crash as free() is called for NULL pointer. Answer: (B) Explanation: free() can be called for NULL
1 min read
C | Dynamic Memory Allocation | Question 8
Consider the following program, where are i, j and k are stored in memory? int i; int main() { int j; int *k = (int *) malloc (sizeof(int)); } (A) i, j and *k are stored in stack segment (B) i and j are stored in stack segment. *k is stored on heap. (C) i is stored in BSS part of data segment, j is stored in stack segment. *k is stored on heap. (D)
1 min read
Use of realloc()
Size of dynamically allocated memory can be changed by using realloc(). As per the C99 standard: void *realloc(void *ptr, size_t size); realloc deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object is identical to that of the old object prior to dealloc
2 min read
new vs malloc() and free() vs delete in C++
We use new and delete operators in C++ to dynamically allocate memory whereas malloc() and free() functions are also used for the same purpose in C and C++. The functionality of the new or malloc() and delete or free() seems to be the same but they differ in various ways.The behavior with respect to constructors and destructors calls differ in the
5 min read
If memory allocation using new is failed in C++ then how it should be handled?
In this article, if memory allocation using new is failed in C++ then how it should be handled? When an object of a class is created dynamically using new operator, the object occupies memory in the heap. Below are the major thing that must be keep in mind: What if sufficient memory is not available in the heap memory, and how it should be handled?
3 min read
MCQ on Memory allocation and compilation process
1. What will be the output of the following code? C/C++ Code #include &amp;lt;stdio.h&amp;gt; #include &amp;lt;stdlib.h&amp;gt; int main() { union test { int i; float f; char c; }; union test* t; t = (union test*)malloc(sizeof(union test)); t-&amp;gt;f = 20.60f; printf(&amp;quot;%f&amp;quot;, t-&amp;gt;f); return 0; } (a) Garbage value (b) 20.60000
3 min read
How to Restrict Dynamic Allocation of Objects in C++?
C++ programming language allows both auto(or stack-allocated) and dynamically allocated objects. In Java &amp; C#, all objects must be dynamically allocated using new. C++ supports stack-allocated objects for the reason of runtime efficiency. Stack-based objects are implicitly managed by the C++ compiler. They are destroyed when they go out of scop
2 min read
Alternative of Malloc in C
An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char
4 min read
C++ malloc()
The function malloc() in C++ is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. A malloc() in C++ is a function that allocates memory at the runtime, hence, malloc() is a dynamic memory allocation technique. It returns a null pointer if fails. Syntax: pointer_name = (cast-type*) malloc(si
3 min read
malloc() vs new
Following are the differences between malloc() and operator new.: Calling Constructors: new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10. C/C++ Code #include&lt;iostream&gt; using namespace std; int main() { // Initialization
1 min read
Function Interposition in C with an example of user defined malloc()
Function interposition is the concept of replacing calls to functions in dynamic libraries with calls to user-defined wrappers. What are applications? We can count number of calls to function. Store caller's information and arguments passed to function to track usage. Detect memory leak, we can override malloc() and keep track of allocated spaces.
3 min read
How to deallocate memory without using free() in C?
Question: How to deallocate dynamically allocate memory without using “free()” function. Solution: Standard library function realloc() can be used to deallocate previously allocated memory. Below is function declaration of "realloc()" from "stdlib.h" C/C++ Code void *realloc(void *ptr, size_t size); If "size" is zero, then call to realloc is equiva
2 min read
How does free() know the size of memory to be deallocated?
Consider the following prototype of free() function which is used to free memory allocated using malloc() or calloc() or realloc(). void free(void *ptr); Note that the free function does not accept size as a parameter. How does free() function know how much memory to free given just a pointer? Following is the most common way to store size of memor
1 min read
fork() and memory shared b/w processes created using it
Prerequisite: fork() in C So when we do a fork() what are the sections the two process actually share? Is the heap memory per process? Are the global variables shared? Will malloc return the same address to both? Let us run the program below and take a look at the output of it to clear the questions above. C/C++ Code // C program to demonstrate wor
4 min read
Difference between Static Arrays and Dynamic Arrays
In the Data structure, we know that an array plays a vital role in having similar types of elements arranged in a contiguous manner with the same data type. According to the concept of array, an array can be defined in two ways as per the memory allocation concept. Types of Arrays:There are basically two types of arrays: Static Array: In this type
5 min read
How will you show memory representation of C variables?
Write a C program to show memory representation of C variables like int, float, pointer, etc. Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer.Program: C/C++ Code #include &amp;lt;stdio.h&amp;gt; typedef unsigned char *byte_poin
1 min read
Common Memory/Pointer Related bug in C Programs
Dereferencing an unknown memory location : C programmers mostly use scanf() function to take input, but sometimes a small mistake can bring a bug or even crash whole program. The syntax for scanf() is scanf("%d", &amp;a);. It might be possible to miss a &amp; and write &amp;a as a so now scanf("%d", a); is dereferencing to an unknown location. Now
6 min read
Random Number Memory Game in C
In this article, will design a simple number memory game in the C programming language. It is a simple memory number game where a random number is displayed and is hidden after some time. The task is to guess that displayed number to continue the game. How to Play This Game: Press 1 on your keyboard to start the game.A random positive number is dis
2 min read
How does C allocate memory of data items in a multidimensional array?
The data items in a multidimensional array are stored in the form of rows and columns. Also, the memory allocated for the multidimensional array is contiguous. So the elements in multidimensional arrays can be stored in linear storage using two methods i.e., row-major order or column-major order. Row major order: In row-major order, we store the el
4 min read
IPC through shared memory
Inter Process Communication through shared memory is a concept where two or more process can access the common memory and communication is done via this shared memory where changes made by one process can be viewed by another process. The problem with pipes, fifo and message queue – is that for two process to exchange information. The information h
3 min read
Does Garbage Collection Guarantee that a Program will not Run Out of Memory?
The work of Garbage collection in Java is to automate the process of deleting memory that's no longer in use. But does that mean Java programs are free from memory limit overflow? Well in this article we will discuss it in brief, but first, let's talk about the garbage collection in Java. Garbage Collection:In C/C++, a programmer is responsible for
3 min read