Expert · Debugging and tools · topic 53 of 60 · 25 min
Sanitizers and warnings
Explanation
AddressSanitizer (ASan)
gcc -std=c17 -g -O1 -fsanitize=address -fno-omit-frame-pointer stock.c -o stock && ./stock==7123==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000002c
WRITE of size 4 at 0x60300000002c thread T0
#0 0x55d1… in restock stock.c:14
#1 0x55d1… in main stock.c:31
0x60300000002c is located 0 bytes to the right of 12-byte region [0x603000000020,0x60300000002c)
allocated by thread T0 here:
#0 0x7f3a… in malloc
#1 0x55d1… in main stock.c:27ASan reports heap-buffer-overflow, stack-buffer-overflow, global-buffer-overflow, heap-use-after-free, double-free, and (on Linux) memory leaks at exit. It typically slows a program down about 2× and increases memory use, which is acceptable for tests.
UndefinedBehaviorSanitizer (UBSan)
gcc -std=c17 -g -fsanitize=undefined calc.c -o calc && ./calc
calc.c:9:14: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
calc.c:15:9: runtime error: shift exponent 32 is too large for 32-bit type 'unsigned int'Use both together during development and testing: -fsanitize=address,undefined. ThreadSanitizer (-fsanitize=thread) finds data races in multithreaded code, but cannot be combined with ASan.
Warnings worth turning on
| Flag | Catches |
|---|---|
| -Wall -Wextra | The common set: unused variables, missing returns, sign comparisons, format errors… |
| -Wpedantic | Code that is not strictly standard C |
| -Wshadow | A local variable hiding another with the same name |
| -Wconversion | Implicit conversions that may lose data (double → int, int → char) |
| -Wformat=2 | More printf/scanf format checks |
| -Werror | Treat all warnings as errors (keeps the build clean) |
Static analysis
- gcc -fanalyzer (GCC 10 and later): follows paths through your code and reports leaks, double frees, NULL dereferences and more, without running it.
- clang-tidy: many checks, including bug-prone patterns and CERT C rules.
- cppcheck: a free standalone analyser that is easy to start with.
- Commercial tools (used in automotive and aerospace) check MISRA C and CERT C compliance.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Sanitizers and warnings · 1/6
In this lesson you will catch bugs automatically with sanitizers, warnings and static analysis.
Prefer a video by a teacher? Find free videos on “addresssanitizer undefinedbehaviorsanitizer tutorial gcc fsanitize” on YouTube ↗
In real life: Catching an overflow in a CI pipeline
A company building a C library for parsing GST invoice files runs its test suite twice in CI: once normally and once with -fsanitize=address,undefined. A contributor's change passed the normal tests, but the sanitizer build failed with a stack-buffer-overflow on a long company name. The bug was fixed before it was ever released.
# Makefile fragment
test-asan:
$(CC) -std=c17 -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer $(SRC) tests.c -o tests_asan
./tests_asanPractice (0/3 done)
ASan reports "heap-use-after-free". What happened?
Which sanitizer finds signed integer overflow?
Take the buggy programs from the valgrind and undefined-behaviour topics and build them with -g -fsanitize=address,undefined. Compare the reports with valgrind's (speed and detail). Then compile your best project with -Wall -Wextra -Wpedantic -Wshadow -Wconversion -fanalyzer and fix every warning.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- assert, logging and testing C codeDebugging and tools · same module
- Debugging with gdbDebugging and tools · same module
- Building real projects: CMake, warnings, debuggers and sanitizersC++ Programming (modern C++ and DSA) · Exceptions, concurrency and building projects with CMake
- Compiling with gccGetting started with C
- Undefined behaviourBits, undefined behaviour and safety
- Stack and heapDynamic memory
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Roughly how much does ASan slow a program down?
Answer: About 2×
Much faster than valgrind.
Can ASan and ThreadSanitizer be used in the same build?
Answer: No
Build them separately.
What does -Wconversion warn about?
Answer: Implicit conversions that may lose data
For example double to int.
Should sanitizer builds be shipped to customers?
Answer: No; use them in development and testing
Ship normal hardened builds.
Which tool is typically faster: valgrind or AddressSanitizer?Related
Which sanitizer finds use-after-free bugs?Related
Answer: AddressSanitizer
AddressSanitizer checks memory accesses.
From Building real projects: CMake, warnings, debuggers and sanitizers
Which is the best fix for an overflow found by a sanitizer?Related
Answer: Track sizes and use bounded functions with length checks
Fix the size handling.
What does an exit status of 0 mean?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Debugging and tools” before its exam: assert, logging and testing C code, A method for debugging.
- Module 11 exam: Debugging and tools · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Embedded C, system calls and careers. 60 topics left in the course before the final exam.