The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Dynamic Memory Allocation in C

Dynamic memory management is the process of allocating and freeing up memory during the execution of the program. The declaration char values[ 50 ] allocates memory for 50 characters on the system stack during compile time. What if you don't know the size of array in advance? Here comes dynamic memory allocation of the array on heap during runtime. C provides following functions for dynamic memory management. These functions are defined in < stdlib.h >.

FunctionDescription
malloc ( int num )Allocates an array of num bytes. The allocated memory
( array ) contains garbage values. malloc returns Null
if memory cannot be allocated
calloc ( int num , int element_size )Allocates an array of num elements where each element is
of size element_size. It is similar to malloc but the
allocated memory ( array ) is initialized with 0.
realloc ( void *address, int new_size )Extends the previously allocated memory by new_size.
free ( void *address)Releases the allocated block of memory to the heap.

Dynamically allocating One Dimensional Array
Following program illustrates the use of calloc function to allocate memory for 1 dimensional array and free function to release that memory. It is very important to use free otherwise there will be memory leak i.e allocated memory won't be deallocated and the memory will be held up without any use.

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

int main() {
   int *arr, n = 5, i;
   arr = calloc( n, sizeof(int) ); /* Allocate an array of size 'n' */
   if ( arr == NULL ) {
       printf("\nCouldn't allocate requested memory");
   }
   else {
       for ( i = 0; i < n; i++ ) { /* fill up the array with some values */
          arr[i] = (i + 1) * 10;
       }
       /* display the array */
       printf("Array elements : ");
       for ( i = 0; i < n; i++ ) {
          printf("%d ", arr[i]);
       }
       free(arr); /* deallocate the memory to prevent memory leak */
   }
   return 0;
}

In the above program, we can also use malloc instead of calloc to allocate memory for an array of size n. We will demonstrate the use of malloc function in next program.

Dynamically allocating Two Dimensional Array
Following program illustrates how memory for a two dimensional array is dynamically allocated and freed using calloc and free function. We can use malloc and calloc interchangeably. The only advantage of calloc is that the memory is initialized after allocation.

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

int main() {
   int **mat;
   int rows, cols, i, j;
   printf("Enter the no. of rows : ");
   scanf("%d", &rows);
   printf("Enter the no. of columns : ");
   scanf("%d", &cols);
   /* dynamically allocate memory for a matrix of size m x n */
   mat = malloc( rows * sizeof(int) );
   for ( i = 0; i < rows; i++ ) {
      mat[i] = malloc( cols * sizeof(int) );
   }
   /* input matrix elements */
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         printf("mat[%d][%d] : ", i, j);
         scanf("%d", &mat[i][j]);
      }
   }
   /* display matrix */
   printf("\nYou have entered :- \n");
   for ( i = 0; i < rows; i++ ) {
      for ( j = 0; j < cols; j++ ) {
         printf("%d  ", mat[i][j]);
      }
      printf("\n");
   }
   /* deallocate (free) the memory */
   for ( i = 0; i < rows; i++ ) {
      free(mat[i]);
   }
   free(mat);
   return 0;
}
Run this program in your system to take input at run-time  


Re-allocating memory
In the following program, we allocate memory using malloc to hold a string. Then, we resize the allocated memory using realloc function to hold a larger string. Internally, realloc allocates a new block of memory, copies the contents of old block and frees up the old block of memory.

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

int main() {
    char *str;
    str = malloc(15 * sizeof(char)); /* allocate memory to store 15 chars */
    if (str == NULL) {
       printf("\nMemory couldn't be allocated");
    }
    else {
       strcpy(str, "Hello World! ");
    }
    /* now we want to store a bigger string */
    str = realloc(str, 30 * sizeof(char)); /* resizing the memory */
    if (str == NULL) {
       printf("\nMemory resizing failed");
    }
    else {
         strcat(str, "I am a computer program.");
    }
    printf("\nstr : %s\n", str);
    return 0;
}

Back | Next