Memory can be allocated while the program runs (on the heap) using <stdlib.h>:
malloc(size): allocate memory (contents are random).
calloc(n, size): allocate and set to zero.
realloc(ptr, newSize): resize.
free(ptr): give the memory back.
Always check that allocation succeeded (the pointer is not NULL), and free every block exactly once. Forgetting causes memory leaks.
💡 Key Takeaways: C Memory Management
Mastering C Memory Management helps you write clean and reliable C code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
C Memory Management Code Example
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *nums = malloc(n * sizeof(int));
if (nums == NULL) return 1;
for (int i = 0; i < n; i++) nums[i] = (i + 1) * 10;
nums = realloc(nums, 6 * sizeof(int));
nums[5] = 60;
for (int i = 0; i < 6; i++) printf("%d ", nums[i]);
printf("\n");
free(nums);
return 0;
}
Output
10 20 30 40 50 60
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
C Memory Management Practice Exercises
Check what you learned in “C Memory Management”.
/ 2 solved
Fill in the blank
Give allocated memory back.
(nums);
✓ Correct!Not quite. Try again.
Multiple choice
Which function allocates memory and sets it to zero?