Dynamic Memory Allocation in C Programming: In C programming, dynamic memory allocation is a process that allows programs to allocate memory at runtime. This is crucial for handling variable data sizes or when the amount of memory required is not known in advance. Unlike static memory allocation, dynamic memory allocation gives the programmer flexibility to manage memory efficiently during the execution of a program.
Pointers in C Programming Langauge Link
Table of Contents
What is Dynamic Memory Allocation in C Programming?
DMA acronym for dynamic memory allocation, it is a process that allows programs to allcoate memory at runtime. This is crucial for handling variable data sizes or when the amount of memory required is not known in advance. Unlike static memory allocation, dynamic memory allocation gives the programmer flexibility to manage memory efficiently during the execution of a program. Proper usage of functions like malloc(), calloc(), realloc(), and free() can greatly improve memory management in your applications.
Why Use Dynamic Memory Allocation?
- Flexibility: Memory can be allocated or deallocated as needed, avoiding the limitations of fixed memory sizes.
- Efficiency: It helps in utilizing memory efficiently by allocating only the necessary amount.
- Handling Large Data: Dynamic allocation is particularly useful when working with large data structures like arrays, linked lists, trees, etc.
Functions Used for Dynamic Memory Allocation
C provides four standard library functions to allocate and deallocate memory dynamically from the heap. These functions are declared in the header file.
- malloc(): Allocates a block of memory.
- calloc(): Allocates a block of memory for an array and initializes it to zero.
- realloc(): Resizes the previously allocated memory block.
- free(): Frees the dynamically allocated memory.
malloc() Function
The malloc() function allocates a specified number of bytes of memory. It returns a pointer to the allocated memory, or NULL if the allocation fails.
Syntax:
ptr = (cast-type*) malloc(size_in_bytes);
Example:
int ptr; ptr = (int) malloc(10 * sizeof(int)); // Allocating memory for 10 integers
Here, ptr points to a block of memory capable of holding 10 integers.
If malloc fails, it returns NULL.
calloc() Function
The calloc() function allocates memory for an array of elements and initializes all bytes to zero.
Syntax:
ptr = (cast-type*) calloc(num_of_elements, size_of_each_element);
Example:
int ptr; ptr = (int) calloc(10, sizeof(int)); // Allocating memory for 10 integers and initializing them to 0
If the memory allocation fails, NULL is returned.
realloc() Function
The realloc() function is used to resize the memory block that was previously allocated by malloc() or calloc().
Syntax:
ptr = (cast-type*) realloc(ptr, new_size_in_bytes);
Example:
ptr = (int*) realloc(ptr, 20 * sizeof(int)); // Resizing the memory block for 20 integers
It returns a pointer to the newly allocated memory, or NULL if reallocation fails.
free() Function
The free() function is used to deallocate the memory that was previously allocated by malloc(), calloc(), or realloc().
Syntax:
free(ptr);
Example:
free(ptr); // Deallocating memory
After freeing memory, the pointer becomes invalid and should not be used unless it is reassigned.
Advantages of Dynamic Memory Allocation
- Memory Efficiency: You can allocate exactly the amount of memory you need at runtime.
- Flexible Memory Usage: Dynamic memory allocation is more flexible than static allocation as it supports dynamic data structures like linked lists, trees, etc.
- Avoid Wastage: You can avoid memory wastage that occurs with static allocation where memory is reserved whether it’s needed or not.
Disadvantages of Dynamic Memory Allocation
- Memory Leaks: If you forget to free dynamically allocated memory, it can lead to memory leaks, causing the program to consume unnecessary memory.
- Fragmentation: Frequent allocation and deallocation may lead to fragmentation, where memory is available but scattered in small blocks.
Common Mistakes with Dynamic Memory Allocation
- Forgetting to free memory: Always ensure that memory is deallocated using free() to prevent memory leaks.
- Dereferencing NULL pointers: Check if malloc(), calloc(), or realloc() returns NULL before using the allocated memory.
- Memory mismanagement: Be cautious about accessing out-of-bounds memory or double freeing allocated memory.
Example Program
#include<stdio.h>
#include<stdlib.h>
int main() {
int *ptr;
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory using malloc()
ptr = (int*) malloc(n * sizeof(int));
// Check if memory has been allocated successfully
if (ptr == NULL) {
printf("Memory not allocated.\n");
return 1;
}
// Store elements in the allocated memory
printf("Enter elements: ");
for (i = 0; i < n; ++i) {
scanf("%d", &ptr[i]);
}
// Display the elements
printf("Elements in array: ");
for (i = 0; i < n; ++i) {
printf("%d ", ptr[i]);
}
// Free the allocated memory
free(ptr);
return 0;
}
Summary
Dynamic memory allocation in C is an essential concept, allowing programs to manage memory more effectively. Proper usage of functions like malloc(), calloc(), realloc(), and free() can greatly improve memory management in your applications. However, it requires careful handling to avoid issues like memory leaks and fragmentation.
Frequently Asked Questions (FAQs)
What is dynamic memory allocation in C?
How is dynamic memory allocation different from static memory allocation?
What are the functions used for dynamic memory allocation in C?
malloc() – Allocates memory block.
calloc() – Allocates memory for an array and initializes all elements to zero.
realloc() – Resizes a previously allocated memory block.
free() – Frees the allocated memory.
What is the difference between malloc() and calloc()?
calloc() allocates memory for an array and initializes all the memory to zero.
How do you free dynamically allocated memory?
What happens if we forget to use free()?
Can we use free() on a pointer set to NULL?
What is a memory leak, and how can it be avoided?
What is fragmentation in dynamic memory allocation?
What does realloc() do?
Learn More
Subscribe “JNG ACADEMY” for more learning best content.
Important Links
C Programming Language Lecture-01
C Programming Language Lecture-02
C Programming Language Lecture-03
C Programming Language Lecture-04
C Programming Language Lecture-05
C Programming Language Lecture-06
C Programming Language Lecture-07
C Programming Langauge Lecture-08
Thank You So Much, Guys… For Visiting our Website and Youtube.