Codiqo

Learn C · lesson 43 of 60 · about 8 minutes

Avoiding Memory Bugs

Copy the alert: recognise leaks, dangling pointers, double frees and NULL crashes, and the habits that prevent them.

What you'll learn

  • Spot a memory leak
  • Explain dangling pointers and double frees
  • Set pointers to NULL after freeing

The alert

Now the admin can type an alert on its own line, like disk nearly full. The report keeps a copy on the heap, made by copy_text, which asks for exactly strlen(s) + 1 bytes: one for each character and one for the '\0'. It turns the copy into capitals so the alert stands out, leaving the original line alone, prints it with its size, then frees the copy and sets the pointer to NULL so it can't be used again by mistake.

The usual suspects

| Bug | What happens | Prevention |
|---|---|---|
| Leak | memory is never freed | one free for every malloc |
| Dangling pointer | using memory after free | set the pointer to NULL after freeing |
| Double free | freeing the same block twice | free(NULL) is safe, so NULL it after |
| NULL dereference | following a NULL pointer | check before using |

These bugs don't always crash straight away, which is what makes them dangerous. Tools like sanitizers and Valgrind find them for you.

Safe habits

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

int main(void) {
    char *name = malloc(16);
    if (name == NULL) return 1;
    snprintf(name, 16, "Phoebe");
    printf("%s\n", name);

    free(name);
    name = NULL;

    free(name);
    if (name == NULL) printf("name is safely empty\n");
    return 0;
}

Output

Phoebe
name is safely empty

Who owns the memory?

Decide which part of your program owns each block: the owner is responsible for freeing it. A common pattern is a pair of functions, like list_create() and list_destroy(), so the caller never has to guess.

Tip

free(NULL) does nothing, which is exactly why setting a pointer to NULL after freeing it makes an accidental second free harmless.

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.