Dynamic memory allocation is a fundamental concept in C programming, enabling efficient memory management during runtime. In this comprehensive guide, we will explore the four key functions for dynamic memory allocation in C: malloc
, calloc
, realloc
, and free
. You will gain a deep understanding of these functions, along with real-world examples and their respective outputs.
Introduction to Dynamic Memory Allocation
Dynamic memory allocation allows programs to request memory from the system’s heap at runtime, providing flexibility and adaptability to memory management. These four functions play a crucial role in this process:
1. malloc
(Memory Allocation)
Syntax:
void* malloc(size_t size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int n = 5;
// Allocate memory for an array of integers
numbers = (int *)malloc(n * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Initialize and use the allocated memory
for (int i = 0; i < n; i++) {
numbers[i] = i * 2;
}
// Deallocate the memory when done
free(numbers);
return 0;
}
2. calloc
(Contiguous Allocation)
Syntax:
void* calloc(size_t num_elements, size_t element_size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int n = 5;
// Allocate memory for an array of integers and initialize to zero
numbers = (int *)calloc(n, sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Use the allocated memory (already initialized to zero)
for (int i = 0; i < n; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
// Deallocate the memory when done
free(numbers);
return 0;
}
3. realloc
(Reallocate Memory)
Syntax:
void* realloc(void* ptr, size_t new_size);
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers;
int n = 5;
// Allocate memory for an array of integers
numbers = (int *)malloc(n * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Resize the allocated memory to store 10 integers
numbers = (int *)realloc(numbers, 10 * sizeof(int));
if (numbers == NULL) {
printf("Memory reallocation failed.\n");
return 1;
}
// Deallocate the memory when done
free(numbers);
return 0;
}
4. free
(Memory Deallocation)
Syntax:
void free(void* ptr);
Example:
#include <stdlib.h>
int main() {
int *numbers;
// Allocate memory for an array of integers
numbers = (int *)malloc(5 * sizeof(int));
// Check for allocation success
// Deallocate the memory when done
free(numbers);
return 0;
}