Finding Memory Bugs: Sanitizers & Valgrind
The usual suspects
| Bug | Example |
|---|---|
| Memory leak | new without delete |
| Use-after-free | using a pointer after delete |
| Double free | deleting the same pointer twice |
| Buffer overflow | arr[10] on a 10-element array |
| Dangling reference | returning a reference to a local |
| Uninitialized read | using a variable before giving it a value |
| Data race | two threads writing the same variable |
| Undefined behaviour | signed overflow, null dereference, bad casts |
AddressSanitizer (ASan) ✅
g++ -std=c++20 -g -fsanitize=address -fno-omit-frame-pointer app.cpp -o app
./app
Detects overflows, use-after-free, double free, leaks (LeakSanitizer). Slows the program about 2× — fine for testing.
UndefinedBehaviorSanitizer (UBSan)
-fsanitize=undefined catches signed overflow, invalid shifts, null dereference, misaligned access…
ThreadSanitizer (TSan)
-fsanitize=thread finds data races (can't be combined with ASan).
MemorySanitizer (Clang)
-fsanitize=memory finds reads of uninitialized memory.
Valgrind (Linux/macOS)
valgrind --leak-check=full ./app
No recompilation needed (but -g gives line numbers). Much slower (~20–50×) but very thorough.
Reading a report
ASan prints the type of error, the line where it happened, where the memory was allocated, and where it was freed. Start from the first frame in your own code.
Prevention beats detection ✅
- Containers instead of raw arrays
- Smart pointers instead of new/delete
.at()while learning-Wall -Wextraand treat warnings as errors (-Werror)- Run tests under sanitizers in CI
- Static analysers:
clang-tidy,cppcheck
The examples in this course were all compiled with -fsanitize=address,undefined to make sure they are clean.
Example
#include <iostream>
#include <memory>
#include <vector>
// Each function shows a classic memory bug (commented out) and the safe modern version.
int sum_first_n(const std::vector<int>& v, std::size_t n) {
// BUG: for (size_t i = 0; i <= n; ++i) total += v[i]; // reads one past the end -> ASan: heap-buffer-overflow
int total = 0;
for (std::size_t i = 0; i < n && i < v.size(); ++i) total += v.at(i);
return total;
}
int use_after_free_fixed() {
// BUG: int* p = new int(5); delete p; return *p; // ASan: heap-use-after-free
auto p = std::make_unique<int>(5);
return *p; // freed automatically, after use
}
void leak_fixed() {
// BUG: int* data = new int[100]; (no delete[]) // LeakSanitizer: detected memory leaks
std::vector<int> data(100, 1);
std::cout << " allocated " << data.size() << " ints, freed automatically\n";
}
int& dangling_fixed(std::vector<int>& storage) {
// BUG: int local = 42; return local; // warning: reference to local variable returned
storage.push_back(42);
return storage.back(); // reference into a container that outlives the call
}
long long overflow_fixed(int a, int b) {
// BUG: return a * b; with a = b = 100000 // UBSan: signed integer overflow
return static_cast<long long>(a) * b;
}
int main() {
std::vector<int> v = { 1, 2, 3, 4, 5 };
std::cout << "sum_first_n(v, 5) = " << sum_first_n(v, 5) << '\n';
std::cout << "sum_first_n(v, 99) = " << sum_first_n(v, 99) << " (clamped safely)\n";
std::cout << "use_after_free_fixed() = " << use_after_free_fixed() << '\n';
leak_fixed();
std::vector<int> storage;
storage.reserve(1);
std::cout << "dangling_fixed() = " << dangling_fixed(storage) << '\n';
std::cout << "100000 * 100000 = " << overflow_fixed(100000, 100000) << '\n';
std::cout << "Compiled with -fsanitize=address,undefined: no errors reported\n";
return 0;
}
/* Output:
sum_first_n(v, 5) = 15
sum_first_n(v, 99) = 15 (clamped safely)
use_after_free_fixed() = 5
allocated 100 ints, freed automatically
dangling_fixed() = 42
100000 * 100000 = 10000000000
Compiled with -fsanitize=address,undefined: no errors reported
*/