AnyCompiler

Dynamic Memory

Every other course on this site either has a garbage collector reclaiming memory automatically (Python, JavaScript, TypeScript, Java) or a compiler-enforced ownership system doing it deterministically (Rust), or C++'s RAII convention tying it to object lifetime. C has none of that: malloc(size) requests a block of raw memory from the heap, and it's yours until you explicitly call free() on it.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *numbers = malloc(3 * sizeof(int));
    numbers[0] = 10;
    numbers[1] = 20;
    numbers[2] = 30;
    int sum = numbers[0] + numbers[1] + numbers[2];
    printf("%d\n", sum);
    free(numbers);
    return 0;
}
Output
60

Forgetting to call free() is a memory leak — the memory stays reserved for the rest of the program's life, since nothing reclaims it automatically. Calling free() twice on the same pointer, or using a pointer after freeing it, is undefined behavior. This manual responsibility is the single biggest thing that separates C from every other language on this site.

Next: structs and pointers — combining the last two lessons, and the real compiler error you get from mixing up . and ->.

Practice exercise

Use malloc to allocate an array of 3 ints, set them to 5, 10, 15, sum them, print the total, then free the array.