C Dynamic Memory (malloc/free)
Dynamic memory allocation lets a program request memory while it's running, rather than at compile time. The <stdlib.h> functions malloc(), calloc(), realloc() and free() manage this heap memory.
Unlike local variables, dynamically allocated memory persists until you explicitly free it, so it's your responsibility to release it when it's no longer needed to avoid memory leaks.
type *p = malloc(n * sizeof(type));
free(p);Allocating memory
malloc(size) reserves a block of `size` bytes and returns a pointer to it (or NULL on failure). calloc(count, size) does the same but also zero-initializes the memory.
Freeing memory
Once you're done with dynamically allocated memory, call free(pointer) to return it to the system. Forgetting to free memory causes a memory leak.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = malloc(3 * sizeof(int));
arr[0] = 1; arr[1] = 2; arr[2] = 3;
printf("%d\n", arr[1]);
free(arr);
return 0;
}2malloc reserves space for 3 ints on the heap, used like a normal array, then freed.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p = malloc(sizeof(int));
if (p == NULL) {
printf("Allocation failed\n");
return 1;
}
*p = 42;
printf("%d\n", *p);
free(p);
return 0;
}42Always check malloc's return value for NULL before using the pointer.
Key points
- malloc() allocates uninitialized heap memory; calloc() zero-initializes it.
- Always check malloc's return value for NULL to detect allocation failure.
- free() releases memory back to the system when you're done with it.
- Forgetting to free() causes memory leaks over a program's lifetime.
