C Dynamic Memory Allocation Tutorial
Dynamic memory allocation in C allows you to allocate memory during program execution. This tutorial explains how to use malloc, calloc, realloc, and free functions for memory management.
1. malloc() Function
malloc is used to allocate a block of memory of specified size. It returns a pointer to the allocated memory, or NULL if allocation fails:
void *malloc(size_t size);
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(5 * sizeof(int)); // Allocates memory for 5 integers
if (arr == NULL) {
printf("Memory allocation failed\\n");
return 1;
}
// Initialize the allocated memory
for (int i = 0; i < 5; i++) {
arr[i] = i * 10;
}
// Print the values
for (int i = 0; i < 5; i++) {
printf("%d\\n", arr[i]);
}
free(arr); // Free the allocated memory
return 0;
}
2. calloc() Function
calloc allocates memory for an array of elements, initializing all bits to 0:
void *calloc(size_t num, size_t size);
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)calloc(5, sizeof(int)); // Allocates memory for 5 integers and initializes to 0
if (arr == NULL) {
printf("Memory allocation failed\\n");
return 1;
}
// Print the values (all should be 0)
for (int i = 0; i < 5; i++) {
printf("%d\\n", arr[i]);
}
free(arr); // Free the allocated memory
return 0;
}
3. realloc() Function
realloc is used to resize a previously allocated memory block:
void *realloc(void *ptr, size_t size);
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\\n");
return 1;
}
// Resize the allocated memory block to hold 10 integers
arr = (int *)realloc(arr, 10 * sizeof(int));
if (arr == NULL) {
printf("Memory reallocation failed\\n");
return 1;
}
// Initialize the resized array
for (int i = 5; i < 10; i++) {
arr[i] = i * 10;
}
// Print the values
for (int i = 0; i < 10; i++) {
printf("%d\\n", arr[i]);
}
free(arr);
return 0;
}
4. free() Function
Once memory is no longer needed, it should be freed using the free function to prevent memory leaks:
void free(void *ptr);
Always call free after dynamically allocated memory is no longer required.
5. Conclusion
Dynamic memory allocation is an essential concept in C, allowing you to allocate memory at runtime. Using functions like malloc, calloc, realloc, and free effectively ensures that memory is managed properly, avoiding memory leaks and errors.