Lesson 1 of 2 · Dynamic Memory · 3 min read · Updated

malloc and free

Ask for memory when you need it, and hand it back when you are done.

Every array so far had its size fixed when you wrote the code. int marks[5] holds five numbers, always.

But what if you do not know how many until the program runs — the user says how many students there are, or a file turns out to have 400 lines? That is what dynamic memory is for.

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

int main(void)
{
    int n;

    printf("How many numbers? ");
    scanf("%d", &n);

    int *marks = malloc(n * sizeof(int));

    if (marks == NULL) {
        printf("Out of memory\n");
        return 1;
    }

    for (int i = 0; i < n; i++) {
        marks[i] = i * 10;
    }

    printf("Last: %d\n", marks[n - 1]);

    free(marks);
    return 0;
}

What each part does

  1. #include <stdlib.h>

    malloc and free live here, not in stdio.h. Forgetting this include is the first error most people hit.

  2. n * sizeof(int)

    malloc counts in bytes, not elements. sizeof(int) asks the compiler how big an int is on this machine, so the same code is correct everywhere.

  3. if (marks == NULL)

    malloc returns NULL when it cannot find the memory. Using the pointer without checking crashes the program — and on a small allocation it will seem to work for years before it does.

  4. marks[i] = i * 10;

    Once you have the pointer, use it exactly like an array. Square brackets work on a pointer, as you saw in the pointers topic.

  5. free(marks);

    Hands the memory back. Until you do, the program keeps holding it — even after you stop using it.

The stack and the heap

An ordinary local variable lives on the stack. It appears when the function starts and vanishes when the function returns — you do not manage it, and you cannot make it outlive the function.

Memory from malloc lives on the heap. It stays until you call free, whatever functions come and go. That is the point: it is how a function can build something and hand it back to its caller.

Warning

Never return a pointer to a local variable. The variable dies when the function returns, and the pointer then points at memory that belongs to something else. The program may appear to work — which is what makes this bug so unpleasant.

Why is sizeof(int) used in malloc(n * sizeof(int))?

Create a free account to save your progress, or sign in.