Dynamic Memory Allocation in C

Dynamic Memory Allocation in C

7 mins read2.1K Views Comment
Updated on Dec 11, 2023 16:23 IST

The memory space occupied by variables and arrays in a system’s memory remains fixed during a program’s execution, even if the allocated space at compile-time proves insufficient. The concept of Dynamic Memory Allocation in C was introduced to address this issue. This allows for allocation and de-allocation of memory during runtime in C.

dynamic memory allocation

 

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:

So, without further ado, let’s get started!

Understanding Memory Management in C

Memory management in C programming works by utilizing two types of memory: static memory and dynamic memory. These memory types are managed by the operating system, which allocates and de-allocates memory blocks either at compile-time or runtime. When allocated during compile-time, it is stored in static memory and referred to as static memory allocation. Conversely, memory allocated during runtime is stored in dynamic memory and is known as dynamic memory allocation.

Explore free C programming courses

Here’s a table summarizing the differences between static and dynamic memory allocation in C:

Static Memory Allocation Dynamic Memory Allocation
Allocated at compile-time Allocated at runtime
Memory size is fixed and predetermined Memory size can be changed during runtime
Memory is stored in the stack section of memory Memory is stored in the heap section of memory
Memory is automatically deallocated when a function returns or the program exits Memory must be explicitly deallocated using functions such as free()
Cannot handle unpredictable data size Can handle unpredictable data size by allocating memory as needed
More efficient in terms of processing time Less efficient in terms of processing time

The main difference between static and dynamic memory allocation is when the memory is allocated and how much control the programmer has over the memory allocation process.

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:

Method Description
malloc() Allocates a single block of requested memory.
calloc() Allocates multiple blocks of requested memory.
realloc() Reallocates the memory occupied by malloc() or calloc() functions.
free() Frees the dynamically allocated memory.

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:

Recommended online courses

Best-suited Other Programming Languages courses for you

Learn Other Programming Languages with these high-rated online courses

Free
10 hours
– / –
– / –
70.5 K
8 months
– / –
60 hours
4.58 K
5 weeks
29 K
8 months
– / –
31 hours

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);

  • size is 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 pointer.

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


 
#include
#include
int main() {
int n, i;
int *ptr;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Allocate memory for 'n' elements using malloc()
ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}
printf("The elements you entered are: ");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
// Deallocate the memory using free()
free(ptr);
return 0;
}
Copy code

Output:


 
Enter the number of elements: 5
Enter the elements: 3 5 7 9 11
The elements you entered are: 3 5 7 9 11
Copy code

In this example, the user is prompted to enter the number of elements they want in the array. Then, the malloc() function is used to dynamically allocate memory for n elements of type int. If the memory allocation is successful, the user is prompted to enter the elements, which are then stored in the dynamically allocated memory. Finally, the free() function is used to deallocate the memory.

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-type is the type you want to cast the allocated memory to (for example, int* or float*)
  • n is the number of blocks to be allocated
  • size is 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;
printf("Enter the number of elements: ");
scanf("%d", &n);
// Allocate memory for 'n' elements using malloc()
ptr = (int *)malloc(n * sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &ptr[i]);
}
printf("The elements you entered are: ");
for (i = 0; i < n; i++) {
printf("%d ", ptr[i]);
}
// Deallocate the memory using free()
free(ptr);
return 0;
}
Copy code

 

Output:

Memory successfully allocated using malloc.

The elements of the array are: 1, 2, 3, 4, 5,

As we can see in the above example. the program dynamically allocates memory for an array of 5 integers using the malloc () function and initializes each element with a value.

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);

  • ptr is a pointer to the memory block previously allocated using malloc() or calloc().
  • size is 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;
// Allocating memory for 5 integers
ptr = (int*)calloc(5, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {
// Memory has been successfully allocated
printf("Memory successfully allocated using calloc.\n");
// Initializing the allocated memory
for (int i = 0; i < 5; i++)
*(ptr + i) = i + 1;
// Printing the elements of the array
printf("The elements of the array are: ");
for (int i = 0; i < 5; i++)
printf("%d, ", *(ptr + i));
}
return 0;
}
Copy code

Output:

Elements of the array: 1, 2, 3, 4, 5,
Elements of the array after reallocation: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

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, ptr is 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:

Feature malloc() calloc()
Functionality Allocates single block of requested memory Allocates multiple blocks of requested memory
Syntax void *malloc(size_t size); void *calloc(size_t nmemb, size_t size);
Initial Value Uninitialized Initializes all the allocated memory to 0
Return Value Pointer to the first byte of the allocated memory Pointer to the first byte of the allocated memory
Time Complexity O(1) O(n) where n is the number of blocks

Note: “size_t” is an unsigned integer data type in C that is used to represent the size of objects in bytes.

Endnotes

Dynamic Memory Allocation is a crucial topic as it is related to many data structures, such as linked lists, stacks, queues, and trees. Hope this article was helpful for you to understand dynamic memory allocation in C Programming. Explore our C articles to find out more about the language and consolidate your knowledge of the fundamentals.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio