Dynamic Memory Allocation in C Programming


In this tutorial, you will learn in-depth about dynamic memory allocation in C programming with calloc(), malloc(), realloc() and free().

dynamic memory allocation in c programming

Dynamic memory allocation in C programming is the powerful feature that uses standard library functions to work.

As the name suggests, dynamic memory allocation provides programmer ability to obtain memory space during execution of the program to hold data and to release used memory space when no longer needed. Generally, memory space is used to add a node to a data.

You might be wondering, where the memory is actually allocated in computer memory?

Let me explain memory allocation process:

Dynamic Memory Allocation in C


There is permanent storage, Heap, and Stack.

memory allocation diagram c

 

Permanent Storage


In this section, global variables and static variables that are initialized by the programmer and executable instructions are stored.

This part of the memory is located below the heap and stack memory because it prevents overwriting of heap and stack overflow.

Stack


In this section, local variable or automatic variables and information regarding the address of function call are stored such as stack pointer.

Heap


This is the part of memory where dynamic memory allocation takes place.

Now, for dynamic memory allocation following standard library functions are essential that are defined in the standard library stdlib.h.

Standard library functions used in dynamic memory allocation (DMA)

malloc()
allocates requested number of bytes and return pointer of type void to allocated memory.
calloc( )
dynamically allocates memory space for the array, initializes to zero and return a pointer to the memory location
free( )
deallocates previously used memory
realloc(  )
modify the size of previously allocated memory
 

C malloc()


This function reserves the number of bytes in memory that is supplied as an argument and returns a pointer of type void to the reserved memory.

A pointer of type void* can be assigned to a variable of any type.

Syntax of malloc()

newPtr = void* malloc( byte-size );

where,

       newPtr = pointer of type void

      byte-size = size of memory in the number of bytes

Example:

newPtr = (int*) malloc( 10 * sizeof(int) );

The above statement allocates area in the memory that is equivalent to 10 times the size of integer and stores a pointer to the allocated memory in variable newPtr.

If the memory space is not available, it returns NULL pointer.

Common Programming Error
If you try to free memory that is not allocated dynamically using malloc results in error.

 

C calloc()


This function is used to dynamically allocate memory for arrays.

As we know that arrays are static data structures hence calloc is used to create dynamic arrays.

Syntax of calloc()

newPtr = void* calloc( n, size );

where,

       newPtr = pointer of type void

      n = number of elements

      size = size of each element

For example:

newPtr = (int*) calloc( 10, size0f(int));

The above statement creates an array of 10 elements each of size equivalent to the integer.

Common Programming Error
Program will crash if you refer to the memory that has been freed.

 

Programming Tips
The main difference between malloc and calloc is that calloc clears the memory it allocates whereas malloc does not.
Similarly, calloc() initializes the memory with 0 whereas malloc() initializes with garbage value

 

C free()


This function deallocates the reserved memory. It frees the memory.

Syntax of free()

free( newPtr );

where,

       newPtr = pointer locating memory location.

Programming Tips
If you had allocated memory using dynamic memory allocation then use free function to deallocate that reserved memory.

 

C realloc()


This function modifies the size allocated previously by malloc, calloc or realloc.

It does not modify the content of an object provided that the amount of size is greater than modified size.

Syntax of realloc()

Ptr = realloc( Ptr, size );

where,

   Ptr = pointer to the original object

   size = new size of the object

relloc() function tries to allocate the new block of memory.

Common Programming Error
Try to avoid zero-sized allocation while using malloc, calloc or realloc.

 

Example: C program to demonstrate the use of calloc() and free()

Program to find greatest number using calloc

//Use of calloc() in C programming

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int size, i;
   int *numPtr; //declaring pointer variable

   printf("Enter total number of elements: ");
   scanf("%d", &size);

   //numPtr points to the first block of memory allocated by calloc of size int
   numPtr = (int*) calloc(size, sizeof(int));

   //checking whether memory is allocated or not
   if(numPtr == NULL)
   {
      printf("\nErorr !!! (Not enough space)");
      exit(0);
   }

   printf("\nPlease enter elements:\n");

   //for loop to store each elements
   for(i = 0; i < size; i++)
   {
      scanf("%d", numPtr + i);
   }

   for(i = 1; i < size; i++)
   {
      if(*numPtr < *(numPtr + i))
      *numPtr = *(numPtr + i);
   }

   printf("\nGreatest element: %d\n", *numPtr);

   free(numPtr); //free reserved space

   return 0;
}

Output

calloc in c

Example: C program to demonstrate the use of malloc() and realloc()

//Use of malloc and free in Dynamic Memory Allocation

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int size, resize, i;
   int *numPtr; //declaring pointer variable

   printf("Please enter size of array: ");
   scanf("%d", &size);

   //allocation memory for array
   numPtr = (int*) malloc(size * sizeof(int));

   //checking whether memory is allocated or not
   if(numPtr == NULL)
   {
      printf("\nError !!! (Not enough space)");
      exit(0);
   }

   printf("\nEnter array elements:\n");

   for(i = 0; i < size; i++)
   {
      scanf("%d", numPtr + i);
   }

   printf("\nElements of array you entered:\n");

   //displaying array elements
   for(i = 0; i < size; i++)
   {
      printf("%3d", *(numPtr + i));
   }

   printf("\n\nEnter new size of array: ");
   scanf("%d", &resize);

   //reallocating array size using new number
   numPtr = realloc(numPtr, resize * sizeof(int));

   if(numPtr == NULL)
   {
      printf("\nError !!! (Not enough space)");
      exit(0);
   }

   printf("\n\nElements of resized array:\n");

   //displaying array of resized array
   for(i = 0; i < resize; i++)
   {
      printf("%3d", *(numPtr + i));
   }

   printf("\n\n");

   free(numPtr); //free reserved memory
   return 0;
}

Output

malloc and realloc in c

Explanation

In the above program, malloc is used to create a dynamic array with 5 elements.

The important step is to check whether the memory space is allocated or not by testing for NULL pointer.

if(numPtr == NULL)
 {
    printf("\nError !!! (Not enough space)");
    exit(0);
 }

Here, numPtr points to the first location in the memory block.

Similarly, realloc is used to resize dynamic array to 3 and data in elements 4 and 5 are truncated as shown in the output above.