C Workshop · Free and Leak
Lesson C

Free and Leak

If you malloc and never free, the program leaks. free once, then do not touch the pointer.

What it is

The correct life of a heap block is malloc, use, free. A leak is forgetting free (or losing the pointer). This lesson also sets p = NULL after free so you are less likely to use or free it again.

Approach

  1. malloc.
  2. Use the memory.
  3. free(p). Do not use *p after that.

Where this is used in the real world

Diagram

1

malloc

live

2

use

print 7

3

free

dead

4

no leak

done

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2#include <stdlib.h>
3int main(void) {
4    int *p = malloc(sizeof(int));
5    if (!p) return 1;
6    *p = 7;
7    printf("%d\n", *p);
8    free(p);
9    p = NULL;
10    return 0;
11}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. Correct order is:

Use then free.

2. After free, p = NULL helps because:

Dangling pointer hygiene.

3. A leak is:

Lost block.

4. free(NULL) is:

Safe.

5. Another kind, realloc(p, bigger):

May relocate.