Dynamic memory allocation is a crucial concept in C programming. It allows programs to request memory at runtime, providing flexibility and efficient resource management.
Static memory allocation has limitations. Dynamic allocation enables programs to:
malloc()
allocates a specified number of bytes and returns a pointer to the allocated memory.
int *ptr = (int*) malloc(5 * sizeof(int));
calloc()
allocates memory for an array of elements, initializing them to zero.
int *ptr = (int*) calloc(5, sizeof(int));
realloc()
changes the size of previously allocated memory.
ptr = (int*) realloc(ptr, 10 * sizeof(int));
free()
deallocates the memory previously allocated by malloc, calloc, or realloc.
free(ptr);
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n = 5;
// Allocate memory for 5 integers
arr = (int*) malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Use the allocated memory
for (int i = 0; i < n; i++) {
arr[i] = i * 10;
}
// Print the array
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
// Free the allocated memory
free(arr);
return 0;
}
While dynamic memory allocation is powerful, it requires careful management. Improper use can lead to issues like memory leaks or segmentation faults. Always ensure that allocated memory is properly freed when no longer needed.
Understanding dynamic memory allocation is essential for creating efficient and flexible C programs. It allows for better resource management and enables the creation of complex data structures.