Codiqo

Learn C · lesson 41 of 60 · about 8 minutes

malloc and free

List the processes: ask for memory while the program runs with malloc, and give it back with free.

What you'll learn

  • Allocate memory with malloc
  • Check for NULL
  • Release memory with free

The processes

The admin wants the report to show how much memory the running processes use. But how many processes there are changes from one day to the next, so nobody can fix the size of an array when the code is written. The report reads the count first, then asks malloc for exactly proc_count * sizeof *procs bytes, reads each process's size into them, totals them, finds the biggest with index_of_max, and gives the memory back with free.

Memory on demand

Normal arrays have a size fixed when you write the code. Sometimes you only know how much you need while the program runs, for example after asking the user.

malloc(bytes) from stdlib.h reserves that many bytes on the heap and returns a pointer to them. When you've finished, free(pointer) gives them back.

int *a = malloc(n * sizeof *a); reserves room for n ints.

An array sized at run time

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

int main(void) {
    int n;
    scanf("%d", &n);
    int *squares = malloc(n * sizeof *squares);
    if (squares == NULL) {
        printf("Out of memory\n");
        return 1;
    }
    for (int i = 0; i < n; i++) squares[i] = (i + 1) * (i + 1);
    for (int i = 0; i < n; i++) printf("%d ", squares[i]);
    printf("\n");
    free(squares);
    return 0;
}

Output

1 4 9 16 25

The rules

1. Always check whether malloc returned NULL (it means there's no memory left)
2. Every malloc needs exactly one matching free
3. Never use memory after freeing it

calloc(n, size) works like malloc but also sets every byte to zero.

Tip

sizeof *squares means "the size of what squares points to". If you later change the type, the malloc line stays correct.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.