Skip to content

C Memory Management

Dynamic memory allocation allows programs to request memory at runtime.

1. Memory Allocation Functions

c
#include <stdlib.h>

int *ptr = (int*)malloc(sizeof(int) * 10);  // allocate
if (ptr == NULL) {
    // handle allocation failure
}

free(ptr);  // deallocate
ptr = NULL;  // avoid dangling pointer

2. calloc

c
int *ptr = (int*)calloc(10, sizeof(int));  // allocate and initialize to zero

3. realloc

c
ptr = (int*)realloc(ptr, sizeof(int) * 20);  // resize

4. Memory Leaks

Always free allocated memory to avoid memory leaks:

c
int *data = malloc(100);
// use data
free(data);  // don't forget!

Content is for learning and research only.