Programmer Coding

Dynamic Memory Allocation in C Language

Dynamic Memory Allocation?

Memory addresses from variables and arrays in system memory remain constant during runtime, even if time allocation is insufficient. To solve this problem, the concept of dynamic memory allocation was introduced in C language. This allows memory to be allocated and allocated at the C runtime.

In this article, we will learn about the dynamic memory allocation in C using functions such as malloc(), calloc(), realloc(), and free(). We will be covering the following sections:

  • Understanding Memory Management in C
  • Dynamic Memory Allocation in C
  • Malloc() Method
  • Calloc() Method
  • Realloc() Method
  • Free() Method
  • Malloc() vs Calloc() Methods

Understanding Memory Management in C

Memory management in C programming uses two types of memory: static memory and dynamic memory. This type of memory is managed by the operating system, which allocates and allocates blocks of memory during writing or execution. When allocated during compilation, it is stored in static memory called static memory allocation. In contrast, memory allocation at runtime is stored in dynamic memory, called dynamic memory allocation.

Dynamic Memory Allocation in C

Dynamic Memory Allocation refers to the process of allocating or deallocating memory blocks during a program’s runtime. This is achieved through the use of four functions:

These functions are located in the <stdlib.h> header file. Dynamic memory allocation can also be considered a method of utilizing heap memory, where the size of variables or data structures (such as arrays) can be changed during a program’s execution with the help of these library functions.

Now, Let us look at the definition, syntax and C example of each of the above-mentioned functions:

Malloc() Method

malloc() is a function in C that dynamically allocates a block of memory of a specified size (in bytes) in the heap section of memory during the runtime of a C program. It can be found in the <stdlib.h> header file.

Syntax

The syntax of malloc() function in C is shown below:

void *malloc(size_t size);

  • sizeis the size in bytes of the memory block to be allocated.
  • malloc()returns a pointer to the first byte of the allocated memory block. If the memory allocation fails, it returns a NULL

Here’s an example of how to use malloc() to dynamically allocate memory for an array of integers in C:

 

Method      Description

malloc()      Allocates a single block of memory of the specified size.

calloc()       Allocates multiple blocks of memory, initialized to zero, each of the specified size.

realloc()     Reallocates the memory block pointed to by a previously allocated pointer. Can be used to resize memory.

free() Frees the dynamically allocated memory previously allocated using malloc(), calloc(), or realloc().

 

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, i;

int *ptr;

// Prompt the user to enter the number of elements

printf(“Enter the number of elements: “);

scanf(“%d”, &n);

// Allocate memory for ‘n’ elements using malloc

ptr = (int *)malloc(n * sizeof(int));

// Check if memory allocation was successful

if (ptr == NULL) {

printf(“Memory allocation failed.\n”);

return 1; // Exit the program with an error code

}

// Prompt the user to enter the elements

printf(“Enter the elements: “);

for (i = 0; i < n; i++) {

scanf(“%d”, &ptr[i]);

}

// Print the entered elements

printf(“The elements you entered are: “);

for (i = 0; i < n; i++) {

printf(“%d “, ptr[i]);

}

printf(“\n”);

// Deallocate the dynamically allocated memory

free(ptr);

return 0; // Exit the program successfully

}

Output

Enter the number of elements: 5

Enter the elements: 1 2 3 4 5

The elements you entered are: 1 2 3 4 5

Calloc() Method

The calloc() function in C is used to dynamically allocate a contiguous block of memory in the heap section. Unlike malloc(), calloc() is used to allocate multiple blocks of memory, typically to store an array of elements.

Syntax

The syntax of calloc() function in C is shown below:

(cast-type*) calloc(n, size);

  • cast-typeis the type you want to cast the allocated memory to (for example, int* or float*)
  • nis the number of blocks to be allocated
  • sizeis the size of each block in bytes

Here’s an example of how to use calloc() to dynamically allocate memory for an array of 5 integers in C:

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

int main() {
int n, i;
int *ptr;

// Prompt the user to enter the number of elements
printf(“Enter the number of elements: “);
scanf(“%d”, &n);

// Allocate memory for ‘n’ elements using calloc
ptr = (int *)calloc(n, sizeof(int));

// Check if memory allocation was successful
if (ptr == NULL) {
printf(“Memory allocation failed.\n”);
return 1; // Exit the program with an error code
}

// Print the allocated elements (initialized to zero)
printf(“The elements after calloc are: “);
for (i = 0; i < n; i++) {
printf(“%d “, ptr[i]);
}
printf(“\n”);

// Deallocate the dynamically allocated memory
free(ptr);

return 0; // Exit the program successfully
}

Output:

Enter the number of elements: 5
The elements after calloc are: 0 0 0 0 0

Realloc() Method

realloc() is a function in C that allows you to change the size of a previously allocated memory block. This function can be used to increase or decrease the size of a block of memory that was previously allocated using either malloc() or calloc(). It can also be used to allocate or de-allocate a memory block on its own completely.

Syntax

The syntax of realloc() function in C is shown below:

void *realloc(void *ptr, size_t size);

  • ptris a pointer to the memory block previously allocated using malloc() or calloc().
  • sizeis the new size for the memory block, in bytes. The function returns a pointer to the newly allocated memory block. If the reallocation fails, the function returns NULL.

Here’s an example of how to use realloc() to dynamically allocate memory in C:

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

int main() {
int *ptr;
int n1 = 5, n2 = 10, i;

// Allocate memory for an array of 5 integers
ptr = (int *)malloc(n1 * sizeof(int));
if (ptr == NULL) {
printf(“Memory allocation failed.\n”);
return 1;
}

// Initialize the array
for (i = 0; i < n1; i++) {
ptr[i] = i + 1;
}

// Print the original array
printf(“Original array: “);
for (i = 0; i < n1; i++) {
printf(“%d “, ptr[i]);
}
printf(“\n”);

// Resize the array to hold 10 integers
ptr = (int *)realloc(ptr, n2 * sizeof(int));
if (ptr == NULL) {
printf(“Memory reallocation failed.\n”);
return 1;
}

// Print the resized array
printf(“Resized array: “);
for (i = 0; i < n2; i++) {
printf(“%d “, ptr[i]);
}
printf(“\n”);

// Deallocate the memory
free(ptr);

return 0;
}

Output:

Original array: 1 2 3 4 5
Resized array: 1 2 3 4 5 0 0 0 0 0

This example demonstrates how to use realloc() to increase the size of an array previously allocated using malloc(). The program first allocates 5 integers using malloc(), and then reallocates the array to 10 integers using realloc(). The reallocated array is displayed on the screen.

Free() Method

The free() method in C is used to deallocate a memory block previously allocated by malloc() or calloc() functions during the execution of the program. It frees up the occupied memory so that it can be reused again.

Syntax

The syntax of free() function in C is shown below:

void free(void *ptr);

  • Here, ptris a pointer to the memory block that needs to be deallocated.

Here’s an example of how to use free() to dynamically deallocate memory in C:

In the above example, malloc() is used to allocate memory for an integer array of size 5 and free() is used to de-allocate that memory block.

Malloc() Vs Calloc() Methods

Here is a comparison table between malloc() and calloc() in C:

Leave a Comment

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

Scroll to Top