Dynamic Memory Allocation in C

Share Your Love

As C is a structured language, it contains some predefined programming rules. Changing the size of an array is one of them. A collection of items stored in contiguous memory spaces is referred to as an array.

array in c

The length (size) of the array above made is 9, as can be observed. But what if there’s a need to adjust the length (size). As an example,

  • In the case that only 5 elements are required to be entered into this array. The remaining four indices in this array are simply wasting RAM in this scenario. As a result, the length (size) of the array must be reduced from 9 to 5.
  • Consider a different scenario. There is a 9-element array with all 9 indices filled in this. However, there are three additional elements in this array that must be entered. In this situation, three extra indices are required. As a result, the array’s length (size) must be increased from 9 to 12.

In C, this approach is known as Dynamic Memory Allocation.

As a result, C Dynamic Memory Allocation can be defined as a technique for changing the size of a data structure (such as an Array) while it is running.

To accomplish these objectives, C provides various functions. To help with dynamic memory allocation in C programming, C provides four library functions that are defined in the stdlib.h header file. They are as follows:

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

Let’s take a closer look at each of them.

C malloc() method:

In C, the “malloc” or “memory allocation” method is used to allocate a single huge block of memory with the specified size dynamically. It returns a void pointer that can be cast into any type of pointer. It does not initialize memory at execution time, therefore each block is initially set to the default garbage value.

Syntax Of malloc():

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.
img
malloc() function

If there isn’t enough space, allocation fails and a NULL pointer is returned.

Example Of malloc():

#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: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,

C calloc() method:

  • In C, the “calloc()” or “contiguous allocation” method is used to allocate a specified number of blocks of memory of a specified type dynamically. It is quite similar to malloc(), but it differs in two ways:
  • It sets the default value for each block to zero.
  • In comparison to malloc(), it has two parameters or arguments.

Syntax Of calloc():

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.
calloc function
calloc() function

If there isn’t enough room, allocation fails and a NULL pointer is returned.

Example Of calloc():

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

The “free” method in C is used to de-allocate memory dynamically. Memory allocated with the malloc() and calloc() procedures is not de-allocated on its own. As a result, anytime dynamic memory allocation happens, the free() function is employed. It frees up memory, which helps to prevent memory waste.

Syntax Of free():

free(ptr);
free function
free() function

Example Of free():

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

In C, the “realloc” or “re-allocation” method is used to change the memory allocation of a previously allocated memory dynamically. In other words, “realloc” can be used to dynamically re-allocate memory if the memory originally allocated with malloc or calloc is insufficient. The existing value is preserved when memory is re-allocated, and new blocks are initialized with the default garbage value.

Syntax Of realloc():

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

If there isn’t enough space, allocation fails and a NULL pointer is returned.

Example Of realloc():

#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 = realloc(ptr, n * sizeof(int));
		// 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 o 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,

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter