Skip to main content

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

 Since C is a structured language, it has some fixed rules for programming. One of it includes changing the size of an array. An array is collection of items stored at continuous memory locations.


As 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 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.

  1. C malloc() method

    “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 initializes each block with default garbage value.

    Syntax:

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

    For Example:

  2. #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 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; 

    1. Output:
      Enter number of elements: 5
      Memory successfully allocated using malloc.
      The elements of the array are: 1, 2, 3, 4, 5,
      
    2. C calloc() method

      “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’.

      Syntax:

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

      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:

    4. #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; 



Comments

Popular posts from this blog

System Analysis and Design Elias M. Awad (Unit - 1)

Systems development is systematic process which includes phases such as planning, analysis, design, deployment, and maintenance. example :- Computer System , Business System , Hotel , Library , College. Audience This tutorial will help budding software professionals to understand how a system is designed in a systematic and phased manner, starting from requirement analysis to system implementation and maintenance. Prerequisites This tutorial is designed for absolute beginners and hence there are no prerequisites as such, however it is assumed that the reader is familiar with the fundamentals of computers. System   Systems development is systematic process which includes phases such as planning, analysis, design, deployment, and maintenance. Here, in this tutorial, we will primarily focus on − Systems analysis Systems design Systems Analysis It is a process of collecting and interpreting facts, identifying the problems, and decomposition of a system into its components. System analy...

Doubly Linked List - Data Structure

                           Doubly Linked List A doubly linked list is a  linked list data structure that includes a link back to the previous node in each node in the structure . This is contrasted with a singly linked list where each node only has a link to the next node in the list. List is a variation of Linked list in which navigation is possible in both ways, either forward and backward easily as compared to Single Linked List. Following are the important terms to understand the concept of doubly linked list. Link  − Each link of a linked list can store a data called an element. Next  − Each link of a linked list contains a link to the next link called Next. Prev  − Each link of a linked list contains a link to the previous link called Prev. LinkedList  − A Linked List contains the connection link to the first link called First and to the last link called Last. Doubly Linked List Represen...

Information Gathering Tool (System Analysis and Design)

  Information gathering tools... Introduction Information Gathering is a very key part of the feasibility analysis process. Information gathering is both an art and a science. It is a science because it requires a proper methodology and tools in order to be effective. It is an art too, because it requires a sort of mental dexterity to achieve the best results. In this article we will explore the various tools available for it, and which tool would be best used depending on the situation. Information Gathering Tools There is no standard procedures defined when it comes to the gathering of information. However, an important rule that must be followed is the following: information must be acquired accurately and methodically, under the right conditions and with minimum interruption to the individual from whom the information is sought. 1. Review of Procedural Forms These are a very good starting point for gathering information. Procedural manuals can give a good picture of the system ...