Memory Management in C

Dynamic Memory Management allows programs to allocate memory during runtime using functions like malloc(), calloc(), realloc(), and free(). It is useful when the amount of memory needed is not known in advance.

Why Use Dynamic Memory?

Basic malloc / free Example


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

int main() {
    int *ptr = (int*) malloc(sizeof(int));

    if (ptr == NULL) {
        printf("Memory allocation failed");
        return 1;
    }

    *ptr = 5;
    printf("%d", *ptr);

    free(ptr);
    return 0;
}

Output

5

Other Memory Functions

Common Mistakes