Tutorial Playlist
Dynamic memory allocation is a crucial concept in C programming that allows you to allocate memory dynamically at runtime. Unlike static memory allocation in C, where the memory is allocated at compile-time and remains fixed, dynamic memory allocation enables you to allocate memory as per your program's requirements and release it when no longer needed. This flexibility is essential for handling variable-sized data structures and optimising memory usage.
In this tutorial, we will explore the basics of dynamic memory allocation in C, including its importance, advantages, and various dynamic memory allocation functions. We will also discuss memory leaks, their causes, detection, and prevention, and provide practical dynamic memory allocation in c programming examples to solidify your understanding.
Dynamic memory allocation refers to the process of dynamically allocating and deallocating memory during a program's execution. It allows you to request memory space as per your program's requirements, use it for storing data, and release it when it is no longer needed. The dynamic memory allocation mechanism in C provides functions such as malloc(), calloc(), realloc(), and free() to manage memory dynamically.
Dynamic memory allocation offers several advantages over static memory allocation in C:
Before we dive into dynamic memory allocation, it's essential to understand how memory management works in C. C divides memory into different segments:
Dynamic memory allocation functions, such as malloc(), calloc(), realloc(), and free(), manage memory in the heap segment.
In C programming, memory can be broadly categorised into two types:
In C, the dynamic memory allocation functions provide a way to allocate and deallocate memory dynamically during program execution. These functions reside in the <stdlib.h> header file. Let's take a closer look at each of these functions:
The malloc() function is used to allocate a block of memory in the heap segment. It takes the number of bytes as an argument and returns a pointer to the allocated memory block. The syntax for malloc() function is as follows:
void* malloc(size_t size); |
Here, size is the number of bytes to allocate, and the return type is void* (generic pointer).
Example:
#include <stdio.h> |
In this example, we allocate memory for n integers using malloc(). The size of memory to allocate is calculated using n * sizeof(int). We then assign the returned memory address to the pointer ptr. After using the allocated memory, we deallocate it using the free() function.
The calloc() function is used to allocate memory and initialise it with zero. It takes two arguments: the number of elements to allocate and the size of each element. The total memory allocated by calloc() is the product of the number of elements and the size of each element. The syntax for calloc() function is as follows:
void* calloc(size_t num, size_t size); |
Here, num is the number of elements to allocate, size is the size of each element, and the return type is void* (generic pointer).
Example:
#include <stdio.h> |
In this example, we allocate memory for n integers using calloc(). The size of memory to allocate is calculated using n * sizeof(int). Unlike malloc(), calloc() initialises the allocated memory with zero. We then access and modify the allocated memory as needed and deallocate it using the free() function.
The realloc() function is used to resize the previously allocated memory block. It takes two arguments: a pointer to the previously allocated memory block and the new size in bytes. The return value is a pointer to the resized memory block, which may or may not be the same as the original pointer. If the resizing fails, realloc() returns NULL without modifying the original memory block. The syntax for realloc() function is as follows:
void* realloc(void* ptr, size_t size); |
Here, ptr is a pointer to the previously allocated memory block, size is the new size in bytes, and the return type is void* (generic pointer).
Example:
#include <stdio.h> |
In this example, we first allocate memory for n integers using malloc(). We then access and modify the allocated memory as needed. Later, we resize the memory block using realloc() to accommodate 10 integers. The new size is calculated using 10 * sizeof(int). If the reallocation is successful, the original pointer may or may not change. Finally, we access and modify the reallocated memory and deallocate it using the free() function.
The free() function is used to deallocate the memory previously allocated using malloc(), calloc(), or realloc(). It takes a single argument, which is a pointer to the memory block, to deallocate. The syntax for free() function is as follows:
void free(void* ptr); |
Here, ptr is the pointer to the memory block to deallocate.
Example:
#include <stdio.h> |
In this example, we allocate memory for n integers using malloc(). After accessing and modifying the allocated memory, we deallocate it using the free() function. It is crucial to deallocate the dynamically allocated memory to prevent memory leaks.
A memory leak occurs when dynamically allocated memory is not deallocated properly after it is no longer needed. Memory leaks can occur due to several reasons, including:
Memory leaks can result in excessive memory usage, degraded program performance, and even program crashes.
To detect and prevent memory leaks, follow these best practices:
To deallocate dynamically allocated memory using the free() function, follow these steps:
Here's an example demonstrating how to deallocate memory using free():
#include <stdio.h> |
While it is essential to deallocate dynamically allocated memory using the free() function, there are situations where you may not be able to or need to deallocate the memory manually. In such cases, the operating system automatically reclaims the memory when the program terminates. However, relying on the operating system to deallocate memory can lead to memory leaks and is generally not recommended.
Dynamic memory allocation finds applications in various areas of C programming, including:
Dynamic memory allocation is a crucial concept in C programming that enables flexible and efficient memory management. By using functions like malloc(), calloc(), realloc(), and free(), you can allocate memory as per your program's needs and release it when no longer required.
Ready to take your C programming skills to the next level? Explore advanced programming courses like Full Stack Software Development Program offered by upGrad and enhance your knowledge of dynamic memory allocation and other important topics in C programming.
Upgrade your skills and become a proficient C programmer today!
Q1: What is the difference between static and dynamic memory allocation in C?
Static memory allocation in C refers to memory allocation at compile-time, where the memory is fixed and remains constant throughout the program's execution. On the other hand, dynamic memory allocation allows memory allocation and deallocation at runtime, providing flexibility in managing memory requirements.
Q2: What are the advantages of dynamic memory allocation in C?
Dynamic memory allocation offers several advantages, including flexibility in memory allocation, efficient memory usage, reduced memory footprint, and the ability to handle dynamic data structures.
Q3: How do I deallocate dynamically allocated memory in C?
To deallocate dynamically allocated memory in C, you need to use the free() function and pass it the pointer to the allocated memory block. This releases the memory and makes it available for reuse.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...