Dynamic Memory Allocation Explained With Simple Example

Dynamic memory allocation is the process of allocating memory at run time by the program based on the need of the program. Dynamic Memory allocation is done from the heap memory available in the system and handling of memory (creation and deletion) is totally handled by the programmer. In case, programmer forgets to cleanup the allocated dynamic memory block, it will lead into memory leak and this memory block will be blocked for further use until program restarts.

Methods available to allocate dynamic memory at run time are

  • malloc () – allocates one memory block of requested size.
  • calloc () – allocates multiple blocks of memory and initialize it with 0.
  • realloc () – increases or decreases the size of previously allocated memory block.
  • free () – frees the memory allocated by above functions.

malloc ()

  • This method is used to allocate one memory block of requested size.
  • In case malloc () fails to allocate memory then it returns NULL pointer.
  • Returns first memory address of allocated memory.
  • Returned pointer type is void *.
  • Allocated memory is not initialized and contains garbage values.
  • It is highly important to verify the returned pointer with NULL check before using it.

Format of malloc () function is as follows:

#include <stdlib.h>
void *malloc(size_t size); /* returns non-null pointer if OK, NULL on error */
/* ---- Example--------------- */
int *p1 = (int *) malloc (sizeof (int)); /* allocate one int */
if (!p1)
{
    printf ("Dynamic memory allocation using malloc failed. \n");
}

calloc ()

  • This method is used to allocate multiple memory block of requested size.
  • In case calloc () fails to allocate memory then it returns NULL pointer.
  • Returns first memory address of allocated memory.
  • Returned pointer type is void *.
  • Allocated memory is initialized with 0.
  • It is highly important to verify the returned pointer with NULL check before using it.

Format of calloc () function is as follows:

#include <stdlib.h>
void *calloc(size_t nobj, size_t size); /* returns non-null pointer if OK, NULL on error */
/* ---- Example--------------- */
int *p3 = (int *) calloc (1, sizeof (int)); /* allocate one int */
if (!p3)
{
    printf ("Dynamic memory allocation using calloc failed. \n");
}

realloc ()

  • This method is used to increases or decreases the size of previously allocated memory block.
  • In case realloc () fails to allocate memory then it returns NULL pointer.
  • Returns first memory address of allocated memory.
  • Returned pointer type is void *.
  • Values of old memory block is copied to new block to ensure no data loss.
  • If previous memory pointer is NULL, then realloc will allocate the memory and returns the pointer.
  • If size is 0, then pointer is freed.
  • It is highly important to verify the returned pointer with NULL check before using it.

Format of realloc () function is as follows:

#include <stdlib.h>
void *realloc(void *ptr, size_t newsize);/* returns non-null pointer if OK, NULL on error */
/* ---- Example--------------- */
p2 = realloc (p2, REALLOC_ARRAY_SIZE * sizeof (int));
if (!p2)
{
    printf ("Dynamic memory allocation using realloc failed.");
}

free ()

  • frees the memory allocated by malloc (), calloc () or realloc ().
  • Free () function returns the memory block to Heap which can be allocated later by same or different program.
  • Memory once freed should never be used.
  • Free () should be called to free the memory allocated by malloc (), calloc () or realloc (). Using free () with some other memory block can crash the system.

Format of free () function is as follows:

#include <stdlib.h>
void free(void *ptr);
    free (p1);
    free (p2);
    free (p3);

Let’s have a look at a program to understand above functions usage better.

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

#define INITIAL_ARRAY_SIZE 20
#define REALLOC_ARRAY_SIZE 40

int main ()
{
	int *p1 = (int *) malloc (sizeof (int)); /* allocate one int */
	if (!p1)
	{
		printf ("Dynamic memory allocation using malloc failed. \n");
	}

	int *p2 = (int *) malloc (sizeof (int) * INITIAL_ARRAY_SIZE); /* allocate array of int of size 20 */
	if (!p2)
	{
		printf ("Dynamic memory allocation using malloc failed.");
	}

	int *p3 = (int *) calloc (1, sizeof (int)); /* allocate one int */
	if (!p3)
	{
		printf ("Dynamic memory allocation using calloc failed. \n");
	}
	printf ("calloc memory is always intialized with 0, checking p3 value [%d]\n", *p3);

	for (int i = 0; i < INITIAL_ARRAY_SIZE; i++)
	{
		p2[i] = i;
	}
	printf ("Inital array value \n");
	for (int i = 0; i < INITIAL_ARRAY_SIZE; i++)
	{
		printf ("%d ", p2[i]);
	}
	printf ("\n");
	p2 = realloc (p2, REALLOC_ARRAY_SIZE * sizeof (int));
	if (!p2)
	{
		printf ("Dynamic memory allocation using realloc failed.");
	}
	printf ("After realloc array value \n");
	for (int i = 0; i < REALLOC_ARRAY_SIZE; i++)
	{
		printf ("%d ", p2[i]);
	}
	printf ("\n");
	free (p1);
	free (p2);
	free (p3);
}

Let’s analyze the output of above program.

calloc memory is always intialized with 0, checking p3 value [0]
Inital array value 
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
After realloc array value 
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

Leave a Reply

Your email address will not be published. Required fields are marked *