Mastering Dynamic Memory Management with malloc and free

 



Working with C means interacting directly with the system's RAM. Dynamic memory allocation is essential whenever you don't know the exact size of your data ahead of time.

Allocation and Deallocation: The Essential Pair

The malloc() function reserves a block of memory on the heap and returns a pointer to it. Once you are done using that memory, you must call free().

C
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n = 5;
    int *arr = (int*) malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }

    // Freeing allocated memory is mandatory
    free(arr);
    arr = NULL; // Prevents dangling pointers
    return 0;
}

Golden Rule: Prevent Memory Leaks

Every call to malloc() or calloc() must have a corresponding call to free(). If you lose the pointer before freeing the memory, that RAM remains blocked until the process terminates.

Post a Comment

0 Comments