Dynamic memory allocation allows you to request memory while the program is running, rather than deciding the size upfront. This is essential when you don't know how much data you'll be handling (like a user-defined list of students).
To use these tools, you must include <stdlib.h>.
FunctionPurposemalloc()Memory allocation. Reserves a block of raw memory.calloc()Clear allocation. Reserves memory and initializes everything to zero.realloc()Re-allocation. Changes the size of a previously allocated block.free()Releases the memory back to the system so you don't have a "memory leak."
Simple Example Dynamic Array
#include <stdio.h>
#include <stdlib.h> // Required for DMA functions
int main() {
int n, i;
int *ptr;
printf("Enter number of elements: ");
scanf("%d", &n);
// 1. Allocate memory using malloc
// We multiply the number of elements by the size of an integer
ptr = (int*)malloc(n * sizeof(int));
// Check if memory allocation failed
if (ptr == NULL) {
printf("Memory not allocated. System out of RAM!\n");
return 1;
}
// 2. Use the memory like a normal array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements are: ");
for (i = 0; i < n; ++i) {
printf("%d ", ptr[i]);
}
// 3. Free the memory!
// Always do this when finished to prevent memory leaks.
free(ptr);
printf("\nMemory successfully freed.\n");
return 0;
}Expected Output:
Enter number of elements: 5
The elements are: 1 2 3 4 5
Memory successfully freed.Important Rules to Remember
The Heap: Dynamic memory lives on the Heap, while regular variables (like
int x) live on the Stack. The Heap is much larger but you have to manage it manually.The Pointer:
mallocreturns avoid*(a generic pointer), which is why we usually cast it to our desired type, e.g.,(int*).The "Free" Rule: Every
mallocorcallocyou write should eventually have a correspondingfree. If you lose the pointer to allocated memory without freeing it, your program will keep eating RAM until it crashes.