C malloc / free – Dynamic Memory Allocation
In C, the malloc()
function is used to allocate memory dynamically during runtime, and the free()
function is used to release the allocated memory. These functions provide a way to manage memory efficiently in programs where the amount of memory needed is not known beforehand.
🔹 malloc() – Memory Allocation
The malloc()
function allocates a block of memory of a specified size. If the memory is successfully allocated, it returns a pointer to the first byte of the memory block. If the allocation fails, it returns NULL
.
📝 Example 1: Using malloc()
This example demonstrates how to allocate memory for an array of integers dynamically using malloc()
, assign values to it, and then free the memory.
#include <stdio.h> #include <stdlib.h> int main() { int *arr; arr = (int *)malloc(5 * sizeof(int)); // Allocating memory for 5 integers if (arr == NULL) { printf("Memory allocation failed\n"); return 1; } // Assigning values to the allocated memory for (int i = 0; i < 5; i++) { arr[i] = i + 1; } // Printing values for (int i = 0; i < 5; i++) { printf("arr[%d] = %d\n", i, arr[i]); } free(arr); // Freeing the allocated memory return 0; }
🔹 free() - Memory Deallocation
The free()
function is used to release previously allocated memory that is no longer needed. After calling free()
, the pointer becomes invalid and should not be used again without being reassigned.
📝 Example 2: Using free()
This example demonstrates how to allocate memory using malloc()
and then release it using free()
after use.
#include <stdio.h> #include <stdlib.h> int main() { int *arr; arr = (int *)malloc(5 * sizeof(int)); // Allocating memory for 5 integers if (arr == NULL) { printf("Memory allocation failed\n"); return 1; } // Assigning values to the allocated memory for (int i = 0; i < 5; i++) { arr[i] = i + 1; } // Printing values for (int i = 0; i < 5; i++) { printf("arr[%d] = %d\n", i, arr[i]); } free(arr); // Freeing the allocated memory printf("Memory has been freed.\n"); return 0; }
⚙️ Important Notes
- Always check if
malloc()
returnsNULL
to handle memory allocation failures. - Never use a pointer after it has been freed. Doing so leads to undefined behavior.
- Using
free()
helps prevent memory leaks by deallocating memory that is no longer needed.
🎯 Recap
Dynamic memory allocation in C using malloc()
and free()
helps you manage memory more efficiently, particularly when working with large datasets or variable-sized structures. Always remember to release memory once it’s no longer needed to avoid memory leaks and ensure your program runs efficiently.