Toolkit: Debuggers, Sanitizers and Profilers
C++ engine bugs come in a few recurring shapes: a crash at a line that looks innocent (memory was corrupted earlier), a value that is wrong only in release builds (undefined behaviour), a hang or a flicker that happens once an hour (a data race), a frame that is slow for no visible reason, and a black screen (the GPU did something you didn't expect). Each shape has a tool that finds it in minutes instead of days.
| Problem | First tool to reach for |
|---|---|
| crash, wrong value | debugger: Visual Studio, gdb, lldb (also inside CLion, VS Code, Xcode) |
| memory corruption, use-after-free, leaks | AddressSanitizer (-fsanitize=address), Valgrind Memcheck |
| undefined behaviour (overflow, bad shifts, misaligned loads) | UndefinedBehaviorSanitizer (-fsanitize=undefined) |
| data races | ThreadSanitizer (-fsanitize=thread) |
| slow CPU frames | Tracy, Superluminal, Optick, perf, Visual Studio profiler, VTune, Valgrind Callgrind |
| wrong or slow GPU frames | RenderDoc, PIX (D3D12), Nsight Graphics, Radeon GPU Profiler, Xcode's Metal debugger |
| crashes on players' machines | minidumps + a crash reporter (Crashpad, Sentry, Backtrace) and saved symbols |
Debuggers
Learn these five things in whichever debugger you use; they cover most sessions:
- Conditional breakpoints (
entity.index == 4127) and hit counts, so you stop on the interesting iteration. - Data breakpoints / watchpoints: stop when a memory address is written. This finds "who overwrote my health value" directly. (
watch -l player->hpin gdb,watchpoint set expression -- &player->hpin lldb, "New Data Breakpoint" in Visual Studio.) - Call stack and frame switching to see how you got here.
- Natvis / pretty printers so your handles, string IDs and containers show readable values. Visual Studio reads
.natvisfiles; gdb uses Python pretty printers and lldb has data formatters. - Attach to a running process and open a crash dump (
.dmpin Visual Studio or WinDbg, core files in gdb/lldb).
Debug builds of engines are often too slow to play. A common compromise is a "Development" configuration: optimisation on (-O2, /O2), asserts and logging on, debug info on (RelWithDebInfo), and selected hot files compiled with lighter optimisation when you need to step through them.
Sanitizers
Sanitizers are compiler instrumentation (Clang and GCC; ASan also in MSVC) that checks memory or thread accesses at run time and prints a precise report at the first bad access, with stack traces of where the memory was allocated and freed.
# GCC / Clang: one sanitizer configuration per CI job (TSan can't be combined with ASan)
cmake -B build-asan -DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer"
cmake -B build-tsan -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_CXX_FLAGS="-fsanitize=thread"# MSVC: Project properties > C/C++ > General > Enable Address Sanitizer, or the flag
/fsanitize=addressRun your automated tests and a scripted play-through under ASan + UBSan regularly, and the job system and asset streaming under TSan. They slow the program down (ASan roughly 2×, TSan more) but turn heisenbugs into reproducible reports.
What a debug heap does, modelled
Before sanitizers, engines and the MSVC debug runtime caught memory bugs by filling memory with recognisable patterns and putting guard bytes around allocations. You will still see these patterns in a debugger, and your own allocators (see Pool Allocators) can use the same trick cheaply in development builds:
#include <cstdint>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <vector>
// a tiny arena with debug fill patterns and guard bytes
class DebugArena {
std::vector<std::uint8_t> mem = std::vector<std::uint8_t>(64, 0);
std::size_t top = 0;
static constexpr std::uint8_t kGuard = 0xFD, kFresh = 0xCD, kFreed = 0xDD;
public:
struct Block { std::size_t offset, size; };
Block alloc(std::size_t size) {
std::memset(&mem[top], kGuard, 4); // guard before
std::memset(&mem[top + 4], kFresh, size); // "uninitialised" pattern
std::memset(&mem[top + 4 + size], kGuard, 4); // guard after
Block b{top + 4, size};
top += size + 8;
return b;
}
std::uint8_t* ptr(Block b) { return &mem[b.offset]; }
void free(Block b) {
check(b, "free");
std::memset(&mem[b.offset], kFreed, b.size); // poison freed memory
}
void check(Block b, const char* when) {
for (int i = 1; i <= 4; i++) {
if (mem[b.offset - i] != kGuard) { std::cout << " " << when << ": guard BEFORE block overwritten\n"; return; }
if (mem[b.offset + b.size + i - 1] != kGuard) { std::cout << " " << when << ": buffer overrun past end of block\n"; return; }
}
std::cout << " " << when << ": guards intact\n";
}
};
int main() {
DebugArena arena;
auto name = arena.alloc(8);
std::uint32_t uninit;
std::memcpy(&uninit, arena.ptr(name), 4);
std::cout << std::hex << std::uppercase;
std::cout << "read before init: 0x" << uninit << " (0xCDCDCDCD = you forgot to initialise)\n";
std::cout << "writing 10 bytes into an 8-byte block:\n";
std::memcpy(arena.ptr(name), "Goblin-42", 10);
arena.check(name, "check");
auto hp = arena.alloc(4);
std::uint32_t health = 100;
std::memcpy(arena.ptr(hp), &health, 4);
arena.free(hp);
std::memcpy(&health, arena.ptr(hp), 4); // use after free
std::cout << "read after free: 0x" << health << " (0xDDDDDDDD = dangling pointer)\n";
}read before init: 0xCDCDCDCD (0xCDCDCDCD = you forgot to initialise)
writing 10 bytes into an 8-byte block:
check: buffer overrun past end of block
free: guards intact
read after free: 0xDDDDDDDD (0xDDDDDDDD = dangling pointer)
A value of 0xCDCDCDCD in the debugger means uninitialised memory, 0xDDDDDDDD means freed memory and 0xFDFDFDFD means you are in the guard area: the patterns tell you the kind of bug at a glance. ASan does the same job far more thoroughly, so use these patterns in your custom allocators and ASan everywhere else.
CPU profilers
| Tool | Platform | Kind | Notes |
|---|---|---|---|
| Tracy | Windows, Linux, macOS, Android | instrumentation + sampling | open source; see Profiling |
| Superluminal | Windows (+ consoles) | sampling + instrumentation | commercial; very fast UI, popular in game studios |
| Optick | Windows, consoles | instrumentation | open source, game-focused |
| Visual Studio Performance Profiler | Windows | sampling | built in; CPU usage, allocations |
| Intel VTune, AMD uProf | x86 | sampling + hardware counters | cache misses, branch mispredictions |
| perf + Hotspot / flame graphs | Linux | sampling | perf record -g ./game then perf report |
| Valgrind Callgrind + KCachegrind | Linux | simulation | exact instruction and cache-miss counts; very slow but deterministic |
| Instruments | macOS, iOS | sampling | Time Profiler, Allocations, Metal System Trace |
GPU debuggers
RenderDoc (open source; Vulkan, D3D11/12, OpenGL, GLES) captures one frame and lets you step through every draw: bound textures, buffers, pipeline state, the mesh before and after the vertex shader, and per-pixel history ("why is this pixel black?"). Launch the game from RenderDoc or inject it, then press the capture key (F12 or Print Screen by default). Name your passes and resources (glObjectLabel, vkSetDebugUtilsObjectNameEXT, glPushDebugGroup/vkCmdBeginDebugUtilsLabelEXT) and captures become readable.
PIX is Microsoft's tool for D3D12 on Windows and Xbox, Nsight Graphics is NVIDIA's frame debugger and GPU trace profiler, Radeon GPU Profiler shows AMD hardware occupancy and barriers, and Xcode's Metal tools cover Apple platforms.
Tip: For Vulkan, keep the validation layers on in every development build and treat each validation message as a bug. Most "works on my GPU, black on yours" problems are validation errors someone ignored.
Test yourself
Which tool finds 'who overwrote this variable' most directly?
- A sampling profiler
- A data breakpoint (watchpoint) on the variable's address
- RenderDoc
- clang-format
You see 0xDDDDDDDD in a pointer's target while debugging an MSVC debug build. What kind of bug is likely?
- Uninitialised memory
- Use after free
- Integer overflow
- A GPU hang
Why run ThreadSanitizer in a separate build from AddressSanitizer?
- TSan is only for Windows
- The two sanitizers can't be combined in one binary
- ASan already detects races
- TSan requires Release builds