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 pointer2. calloc
c
int *ptr = (int*)calloc(10, sizeof(int)); // allocate and initialize to zero3. realloc
c
ptr = (int*)realloc(ptr, sizeof(int) * 20); // resize4. Memory Leaks
Always free allocated memory to avoid memory leaks:
c
int *data = malloc(100);
// use data
free(data); // don't forget!