SyntaxPilot
Courses/C Programming/Lesson 26
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C Programming · Lesson 26 of 30

Memory bugs and how to find them (sanitizers, valgrind)

queued

These are the notes for C episode 26. Some C bugs crash loudly. The dangerous ones don't: the program runs, prints something believable, and is still wrong. In this episode you meet four of these silent memory bugs live (out of bounds, use after free, memory leaks and uninitialised values), learn why C stays silent (undefined behaviour), and then invent the guards that catch them: AddressSanitizer, LeakSanitizer, valgrind, UBSan and plain old -Wall. Programs marked online compiler were compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, glibc 2.39, the same command as the SyntaxPilot compiler) and run as shown. The online compiler can't take extra flags or run valgrind, so the sanitizer and valgrind sessions were run in a normal Linux terminal (gcc 13.3, Valgrind 3.22, Ubuntu 24.04). In those, process ids are written as ==1==, long addresses are shortened, and the C library's start-up frames and ASan's shadow-byte table are left out.

The real-life picture: memory is a hotel

In a hotel In C
A corridor of numbered rooms Memory: bytes, each with an address
Check in: the desk gives you 5 rooms and a key card malloc: you get a block of bytes and a pointer to it
Check out: the rooms go to the next guest free: the block can be handed out again
No guard in the corridor C never checks which bytes you touch

C trusts you completely. Nothing stops you from walking into a room you didn't book, using an old key card, or never checking out. That trust is what makes C fast, and what makes these bugs possible.

Bug 1: one room too far (out of bounds on the stack)

A report card adds five marks, but the loop runs while i <= 5. Index 5 is one past the end: the array has indexes 0 to 4. Reading or writing outside an array is called going out of bounds.

#include <stdio.h>

int main() {
    int marks[5] = {78, 92, 65, 88, 71};
    int total = 0;
    for (int i = 0; i <= 5; i++)
        total += marks[i];
    printf("Total: %d\n", total);
    return 0;
}

Output (online compiler):

main.c:7:23: warning: iteration 5 invokes undefined behavior [-Waggressive-loop-optimizations]
Total: 33158

The total changes slightly from run to run (33158, 33160, 33161 …), because marks[5] is whatever happens to sit next to the array. gcc printed a warning, but a warning doesn't stop the program from compiling and running. Fix: i < 5.

Bug 2: the bug that looks perfect (heap buffer overflow)

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

int main() {
    int n = 5;
    int *marks = malloc(n * sizeof(int));
    for (int i = 0; i <= n; i++)
        marks[i] = 90 + i;
    printf("Last mark: %d\n", marks[n - 1]);
    free(marks);
    return 0;
}

Output (online compiler):

Last mark: 94

No warning, no error, and the answer is right. But the loop writes marks[5], which was never allocated. Writing past the end of a block is a buffer overflow (a buffer is just a block of memory that holds data). On the heap, it scribbles over bytes the allocator uses for its own bookkeeping. This time the program survived; with other data it might crash much later, far from the real bug. Fix: i < n.

Bug 3: the old key card (use after free)

Real-life example. Meera checks into room 101 and gets a key card (the pointer). She checks out (free) but keeps the card. Ravi checks into the same room 101 (malloc reuses the block). Meera's old card still opens the door, and now shows Ravi's things.

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

int main() {
    char *guest = malloc(32);
    strcpy(guest, "Meera");
    printf("Room 101: %s\n", guest);
    free(guest);

    char *next = malloc(32);
    strcpy(next, "Ravi");
    printf("New guest: %s\n", next);

    printf("Room 101: %s\n", guest);
    free(next);
    return 0;
}

Output (online compiler):

Room 101: Meera
New guest: Ravi
Room 101: Ravi

Using memory after it was freed is a use after free. A pointer that still holds the address of freed memory is a dangling pointer. Here guest shows the next guest's data. If guest were one user's bank record and next someone else's, this is exactly how security holes happen. Fix: after free(p); write p = NULL; and never use it again. A NULL pointer crashes loudly at once instead of quietly showing someone else's data.

Bug 4: rooms nobody gives back (memory leak)

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

char *make_ticket(int n) {
    char *t = malloc(32);
    sprintf(t, "TICKET-%04d", n);
    return t;
}

int main() {
    for (int i = 1; i <= 3; i++) {
        char *t = make_ticket(i);
        printf("%s\n", t);
    }
    return 0;
}

Output (online compiler):

TICKET-0001
TICKET-0002
TICKET-0003

Perfect output, but nothing is ever freed. When t goes out of scope at the end of each loop pass, the only pointer to that block is gone, so it can never be freed. Memory you allocated and can no longer free is a memory leak. Three tickets don't matter; a server that leaks on every request slowly fills its memory until the operating system kills it. Fix: free(t); after printing each ticket.

Bug 5: values nobody set (uninitialised variable)

#include <stdio.h>

int main() {
    int marks[5] = {78, 92, 65, 88, 71};
    int total;
    for (int i = 0; i < 5; i++)
        total += marks[i];
    printf("Total: %d\n", total);
    return 0;
}

Output (online compiler):

Total: 394

Correct, by luck. total was never given a starting value, so it is uninitialised: it holds whatever bytes the last user of that memory left behind. Here that happened to be 0. A different compiler, different flags or a different function called just before can make it print garbage. Fix: int total = 0;.

Why C stays silent: undefined behaviour

  • Checking every index, every free and every variable costs time, and C was designed to be fast, so it checks none of them.
  • When a program breaks these rules, the C standard says its behaviour is undefined behaviour (UB): the rules say nothing about what happens.
  • Anything may happen: a garbage value, a crash much later somewhere else, or "it works" today on your computer.
  • So the output can never prove there is no bug. You need a tool that watches every memory access.

AddressSanitizer: a guard in the corridor

Real-life example: a strict hotel.

Strict hotel AddressSanitizer
Warning tape around every booking: step on it and the alarm rings Red zones: poisoned bytes around every block; touching them stops the program
Checked-out rooms stay locked for a while Quarantine: freed blocks aren't handed out again at once, so a use after free is caught
An audit at closing time: who never returned their rooms? LeakSanitizer: lists every block still allocated at exit

A sanitizer is a checker that the compiler builds into your program. Turn AddressSanitizer (ASan) on with one flag, and add -g (episode 21) so reports show file names and line numbers:

gcc -g -fsanitize=address heap.c -o heap
./heap

The program runs about 2 times slower and uses more memory, so use it for testing, not for the version you ship. At the first bad access it stops and prints a report.

Bug 2, caught

$ gcc -g -fsanitize=address heap.c -o heap
$ ./heap
==1==ERROR: AddressSanitizer: heap-buffer-overflow
  on address 0x503000000054 ...
WRITE of size 4 at 0x503000000054 thread T0
    #0 0x55965cd812cc in main heap.c:8

0x503000000054 is located 0 bytes after
  20-byte region [0x503000000040,0x503000000054)
allocated by thread T0 here:
    #0 0x7fbe04cfd9c7 in malloc
    #1 0x55965cd8126c in main heap.c:6

SUMMARY: AddressSanitizer: heap-buffer-overflow heap.c:8 in main
==1==ABORTING

How to read it: 1. What: heap-buffer-overflow, a WRITE of size 4 (one int). 2. Where: in main heap.c:8, the loop body. 3. Whose block: 0 bytes after 20-byte region: five 4-byte ints = 20 bytes, and we wrote just past the end. allocated by ... heap.c:6 shows the malloc.

Bug 3, caught

$ gcc -g -fsanitize=address room.c -o room
$ ./room
Room 101: Meera
New guest: Ravi
==1==ERROR: AddressSanitizer: heap-use-after-free
READ of size 2 at 0x503000000040 thread T0
    #3 0x55f8c57be2e3 in main room.c:15
0x503000000040 is located 0 bytes inside of 32-byte region
freed by thread T0 here:
    #0 0x7f4f3b8fc4d8 in free
    #1 0x55f8c57be284 in main room.c:9
previously allocated by thread T0 here:
    #0 0x7f4f3b8fd9c7 in malloc
    #1 0x55f8c57be23e in main room.c:6

Three stories in one report: where the freed memory was used (line 15), where it was freed (line 9), and where it was first allocated (line 6).

Bug 4, caught by LeakSanitizer

$ gcc -g -fsanitize=address ticket.c -o ticket
$ ./ticket
TICKET-0001
TICKET-0002
TICKET-0003

==1==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 96 byte(s) in 3 object(s) allocated from:
    #0 0x7f79aecfd9c7 in malloc
    #1 0x560c76c52221 in make_ticket ticket.c:5
    #2 0x560c76c52268 in main ticket.c:12

SUMMARY: AddressSanitizer: 96 byte(s) leaked in 3 allocation(s).

Direct leak of 96 byte(s) in 3 object(s): three tickets of 32 bytes, allocated in make_ticket (line 5), called from main (line 12). LeakSanitizer is part of ASan on Linux and runs automatically when the program exits.

valgrind: the CCTV auditor

Real-life example: CCTV on every door. You don't rebuild the hotel; you just watch everything. valgrind (its default tool is called Memcheck) runs your normal program on a simulated processor and checks every instruction. No special compile flag is needed (just -g for line numbers). It is slow, often 20 to 50 times slower, but sees everything, including values used before being set.

Invalid write

$ gcc -g heap.c -o heap
$ valgrind ./heap
==1== Memcheck, a memory error detector
==1== Invalid write of size 4
==1==    at 0x1091D4: main (heap.c:8)
==1==  Address 0x4a7e054 is 0 bytes after a block of size 20 alloc'd
==1==    at 0x4846828: malloc (in vgpreload_memcheck...)
==1==    by 0x1091AC: main (heap.c:6)
Last mark: 94
==1== All heap blocks were freed -- no leaks are possible
==1== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

valgrind reports the error and lets the program continue, so Last mark: 94 still prints. The goal is ERROR SUMMARY: 0 errors.

Definitely lost

$ valgrind --leak-check=full ./ticket
TICKET-0001
TICKET-0002
TICKET-0003
==1== HEAP SUMMARY:
==1==     in use at exit: 96 bytes in 3 blocks
==1==   total heap usage: 4 allocs, 1 frees, 4,192 bytes allocated
==1== 96 bytes in 3 blocks are definitely lost in loss record 1 of 1
==1==    at 0x4846828: malloc (in vgpreload_memcheck...)
==1==    by 0x1091A1: make_ticket (ticket.c:5)
==1==    by 0x1091E8: main (ticket.c:12)
==1== LEAK SUMMARY:
==1==    definitely lost: 96 bytes in 3 blocks

4 allocs, 1 frees: our three tickets, plus one buffer that printf allocated and freed itself. Definitely lost means no pointer to the block exists anymore, so it can never be freed. (valgrind's other categories: indirectly lost = reachable only through a lost block, such as the rest of a lost linked list; possibly lost = only a pointer into the middle of the block remains; still reachable = a pointer still exists at exit.)

Uninitialised values: -Wall and valgrind

$ gcc -Wall -O2 total.c -o total
total.c:7:15: warning: 'total' is used uninitialized [-Wuninitialized]
    7 |         total += marks[i];

$ gcc -g total.c -o total
$ valgrind --track-origins=yes ./total
==1== Conditional jump or move depends on uninitialised value(s)
==1==    by 0x48C81B2: printf (printf.c:33)
==1==    by 0x1091DE: main (total.c:8)
==1==  Uninitialised value was created by a stack allocation
==1==    at 0x109169: main (total.c:3)
Total: 394
  • -Wall turns on most warnings. gcc knew about the bug at compile time; we just never asked.
  • Conditional jump or move depends on uninitialised value(s): a decision (inside printf) was made from a value nobody set. --track-origins=yes adds where the value came from: a stack allocation in main.

UBSan: the undefined behaviour sanitizer

#include <stdio.h>
#include <limits.h>

int main() {
    int views = INT_MAX;
    views = views + 1;
    printf("Views: %d\n", views);
    return 0;
}

Output (online compiler): Views: -2147483648. Signed integer overflow is undefined behaviour, and C said nothing.

$ gcc -g -fsanitize=undefined views.c -o views
$ ./views
views.c:6:11: runtime error: signed integer overflow:
  2147483647 + 1 cannot be represented in type 'int'
Views: -2147483648

-fsanitize=undefined (UBSan) catches undefined behaviour that isn't about memory: signed overflow, shifting by too many bits, division by zero, misaligned or NULL pointer use. Fix: a bigger type (long long) or check before adding (if (views < INT_MAX) views++;). In practice, turn both on together: -fsanitize=address,undefined.

Which tool when?

Tool How Catches Cost
-Wall -Wextra compile flags uninitialised variables, suspicious code free, at compile time
AddressSanitizer -g -fsanitize=address out of bounds (heap, stack, globals), use after free, double free, leaks about 2x slower
UBSan -g -fsanitize=undefined signed overflow, bad shifts, division by zero, NULL misuse small
valgrind valgrind --leak-check=full ./prog heap out of bounds, use after free, leaks, uninitialised values 20-50x slower, no rebuild with flags
  • Use ASan or valgrind, not both at once. Running an ASan program under valgrind fails with ASan runtime does not come first in initial library list; you should either link runtime to your application or manually preload it with LD_PRELOAD.
  • These tools only see code that runs. Test the first item, the last item, the empty case and the biggest case.

Mini project: canteen order bug hunt

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

char *copy_name(const char *s) {
    char *p = malloc(strlen(s));
    strcpy(p, s);
    return p;
}

int main() {
    const char *menu[] = {"Samosa", "Vada Pav", "Chai"};
    char *orders[3];
    for (int i = 0; i < 3; i++)
        orders[i] = copy_name(menu[i]);
    for (int i = 0; i < 3; i++)
        printf("Order %d: %s\n", i + 1, orders[i]);
    free(orders[0]);
    free(orders[1]);
    return 0;
}

There are two bugs. Run it in the online compiler:

main.c:7:5: warning: '__builtin___strcpy_chk' writing one too many bytes into a region of a size that depends on 'strlen' [-Wstringop-overflow=]
...
*** buffer overflow detected ***: terminated

Ubuntu's gcc turns on a cheap check called fortify (_FORTIFY_SOURCE) for functions like strcpy. It tells you that something overflowed, but not which block or why. ASan tells you where and why:

$ gcc -g -fsanitize=address orders.c -o orders
$ ./orders
==1==ERROR: AddressSanitizer: heap-buffer-overflow
WRITE of size 7 at 0x502000000016 thread T0
    #0 0x7fbb648a7922 in strcpy
    #1 0x560516105303 in copy_name orders.c:7
    #2 0x5605161054b5 in main orders.c:15
0x502000000016 is located 0 bytes after
  6-byte region [0x502000000010,0x502000000016)
allocated by thread T0 here:
    #1 0x5605161052ec in copy_name orders.c:6

"Samosa" has 6 letters, so strlen returns 6, but a C string also needs the '\0' at the end: 7 bytes written into 6. Fix 1: malloc(strlen(s) + 1). Run again with ASan:

$ ./orders            # after the + 1 fix
Order 1: Samosa
Order 2: Vada Pav
Order 3: Chai

==1==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 5 byte(s) in 1 object(s) allocated from:
    #1 0x564fe675d2f0 in copy_name orders.c:6
    #2 0x564fe675d4b9 in main orders.c:15

$ ./orders            # after freeing all three
Order 1: Samosa
Order 2: Vada Pav
Order 3: Chai

Fix 2: we freed orders[0] and orders[1] but forgot orders[2] ("Chai", 4 letters + '\0' = 5 bytes). Free in a loop, the same way you allocated. Final version:

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

char *copy_name(const char *s) {
    char *p = malloc(strlen(s) + 1);
    strcpy(p, s);
    return p;
}

int main() {
    const char *menu[] = {"Samosa", "Vada Pav", "Chai"};
    char *orders[3];
    for (int i = 0; i < 3; i++)
        orders[i] = copy_name(menu[i]);
    for (int i = 0; i < 3; i++)
        printf("Order %d: %s\n", i + 1, orders[i]);
    for (int i = 0; i < 3; i++)
        free(orders[i]);
    return 0;
}

Output:

Order 1: Samosa
Order 2: Vada Pav
Order 3: Chai

A silent ASan run is the green light. Extend it: add a fourth dish, and write void free_orders(char *orders[], int n).

Common mistakes

Mistake What you see Why Fix
for (i = 0; i <= n; i++) a[i] = ... ASan: heap-buffer-overflow (or nothing without tools) index n is one past the end i < n
free(p); ... printf("%s", p); ASan: heap-use-after-free; without tools, another block's data p still holds the old address free(p); p = NULL;
malloc(strlen(s)) then strcpy *** buffer overflow detected ***: terminated no room for '\0' malloc(strlen(s) + 1)
malloc with no free LeakSanitizer: detected memory leaks; valgrind: definitely lost the last pointer to the block is lost exactly one free per malloc
int total; total += x; -Wall: 'total' is used uninitialized; valgrind: Conditional jump or move depends on uninitialised value(s) holds leftover bytes int total = 0;
free(p); free(p); ASan: attempting double-free the block was already returned set p = NULL after free (free(NULL) does nothing)
-fsanitize=address without -g in main (/tmp/m26/heap_ng+0x12cc): no line numbers no debug information add -g
int views = INT_MAX; views + 1 UBSan: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int' int can't hold the result long long, or check first

Practice questions

  1. Why can't a correct-looking output prove that a C program has no memory bug?
Answer

Memory bugs are undefined behaviour: the program may still print the right answer by luck (for example, a leftover 0 in an uninitialised variable, or a write into unused bytes past a block). Only a tool that watches memory accesses can show the bug.

  1. Find the bug: char s[5]; strcpy(s, "Hello");
Answer

"Hello" needs 6 bytes (5 letters + '\0'), but s has 5. Use char s[6]; or bigger. ASan reports stack-buffer-overflow.

  1. What is a dangling pointer and how do you defuse it?
Answer

A pointer that still holds the address of memory that was freed (or of a local variable whose function has returned). Set it to NULL right after free, and check for NULL before use.

  1. Free a whole linked list (episode 22) without a use after free.
Answer
void free_list(struct node *head) {
    while (head != NULL) {
        struct node *next = head->next;   // save it BEFORE free
        free(head);
        head = next;
    }
}

Reading head->next after free(head) would be a use after free.

  1. A program prints the right answer but valgrind says 96 bytes in 3 blocks are definitely lost. What do you look for?
Answer

The stack under the message (by ... make_ticket (ticket.c:5)) shows where those blocks were allocated. Find where the pointer returned from there is last used, and free it after that point.

  1. Which flags would you use for every test build?
Answer

gcc -Wall -Wextra -g -fsanitize=address,undefined main.c -o main

Quiz

char *name = malloc(5);
strcpy(name, "Kabir");
printf("%s\n", name);
free(name);

Built with -fsanitize=address, what does ASan report? A) heap-buffer-overflow · B) heap-use-after-free · C) detected memory leaks · D) Nothing

Answer

A) heap-buffer-overflow. "Kabir" is 5 letters plus '\0' = 6 bytes, written into a 5-byte block. gcc 13 even warns at compile time: '__builtin_memcpy' writing 6 bytes into a region of size 5 overflows the destination.

Interview questions

  1. What is undefined behaviour? Give three examples. Behaviour the C standard places no requirements on. Out-of-bounds access, use after free, signed integer overflow, reading an uninitialised variable, dereferencing NULL.
  2. What is the difference between a memory leak and a dangling pointer? A leak is memory still allocated with no pointer left to free it; a dangling pointer is a pointer left over to memory that is no longer allocated.
  3. How does AddressSanitizer detect out-of-bounds accesses? It surrounds every block with poisoned red zones and keeps "shadow memory" recording which bytes are valid; the compiler adds a check before every load and store.
  4. ASan vs valgrind? ASan needs recompiling, is about 2x slower and also checks stack and global arrays; valgrind needs no special build, is 20-50x slower, and finds uninitialised reads. Don't combine them.
  5. Why should you set a pointer to NULL after free? A later use crashes immediately and predictably instead of reading reused memory, and free(NULL) is safe, so a double free becomes harmless.
  6. What does "definitely lost" mean in valgrind? No pointer to the block exists anywhere at exit; it can never be freed.

Glossary

Term Meaning Example
Memory bug A mistake in how a program uses memory writing past an array
Address The number of one byte in memory 0x503000000054
Heap The memory area malloc hands out blocks from malloc(20)
Stack The memory area for local variables of running functions int marks[5]; inside main
Block The bytes one malloc call returns 20 bytes for 5 ints
Buffer A block of memory that holds data char name[32]
Out of bounds Using an index outside an array's valid range marks[5] in a 5-element array
Buffer overflow Writing past the end of a buffer strcpy of 7 bytes into 6
Use after free Using memory after it was freed printf("%s", guest) after free(guest)
Dangling pointer A pointer to memory that is no longer valid guest after free(guest)
Memory leak Allocated memory that can no longer be freed make_ticket result never freed
Double free Calling free twice on the same block free(p); free(p);
Uninitialised A variable that was never given a value int total;
Undefined behaviour (UB) Breaking a rule of C; anything may happen signed overflow
Warning A compiler message that does not stop compilation iteration 5 invokes undefined behavior
-Wall, -Wextra Flags that turn on most compiler warnings gcc -Wall main.c
Sanitizer A checker the compiler builds into your program ASan, UBSan
AddressSanitizer (ASan) Sanitizer for memory errors -fsanitize=address
Red zone Poisoned bytes around a block that trigger an alarm when touched the "tape" around a booking
Quarantine Freed blocks held back from reuse so misuse is caught locked checked-out rooms
LeakSanitizer (LSan) Leak checker that runs at exit (part of ASan on Linux) detected memory leaks
UBSan Sanitizer for undefined behaviour -fsanitize=undefined
valgrind / Memcheck Tool that runs a program on a simulated CPU and checks memory valgrind ./prog
Definitely lost valgrind: no pointer to the block exists at exit the three tickets
Fortify A cheap check Ubuntu's gcc adds to strcpy and friends *** buffer overflow detected ***
-g Keep debug information (file names, line numbers) gcc -g

Summary

  • Memory is a hotel with no guard: malloc checks in, free checks out, and C checks nothing.
  • Four silent bugs: out of bounds, use after free, leaks, uninitialised values. All are undefined behaviour: the output may look right.
  • Always compile with -Wall -Wextra. Test with -g -fsanitize=address,undefined. Use valgrind when you can't rebuild with flags or to find uninitialised reads.
  • Read a report as what, where, whose block.
  • Habits: i < n, malloc(strlen(s) + 1), one free per malloc, p = NULL after free, initialise every variable.
  • Next episode (27): Recursion in C, functions that call themselves, the call stack, and fibonacci done right.