Catalog / Valgrind Cheatsheet
Valgrind Cheatsheet
A comprehensive cheat sheet for Valgrind, a powerful memory debugging and profiling tool for Linux. This guide covers essential Valgrind tools, common options, and practical examples to help you identify and fix memory-related issues in your C/C++ programs.
Valgrind Fundamentals
Core Tools Overview
Memcheck: Detects memory management problems like memory leaks, invalid reads/writes, and use of uninitialized values. |
Basic Memcheck Usage
Command |
Description |
|
Run |
|
Run |
|
Enables basic leak checking (same as |
|
Shows reachable memory blocks at program exit (useful for debugging). |
|
Tracks the origin of uninitialized values (can help find the source of errors). |
Understanding Memcheck Output
Memcheck reports different kinds of errors:
|
Advanced Memcheck Options
Suppressing Errors
Sometimes Valgrind reports errors that are known and acceptable (e.g., from third-party libraries). You can suppress these errors using a suppression file.
|
Example Suppression File Entry:
|
Controlling Verbosity
Option |
Description |
|
Increases verbosity level. Can be specified multiple times for more detail. |
|
Suppresses most output. Useful for automated testing. |
Error Kinds
Valgrind categorizes errors. Key error types include:
|
Profiling with Cachegrind & Callgrind
Cachegrind Basics
Cachegrind simulates the cache of your CPU, providing insights into cache misses, branch prediction, and instruction counts.
This command generates a |
Use
This command displays annotated source code with cache statistics. |
Callgrind for Function-Level Profiling
Command |
Description |
|
Runs |
|
Analyzes Callgrind output, showing function-level performance data. |
|
Graphical tool to visualize Callgrind profiling data. |
Key Metrics in Cachegrind/Callgrind
|
Threading Errors with Helgrind & DRD
Helgrind - Threading Error Detection
Helgrind detects potential threading errors, primarily focusing on data races.
It identifies locations where multiple threads access the same memory without proper synchronization (e.g., locks). |
DRD (Data Race Detector)
DRD is another tool for detecting data races, and often complements Helgrind.
It uses a different algorithm and may find data races that Helgrind misses (and vice versa). |
Interpreting Helgrind/DRD Output
Helgrind and DRD reports highlight the lines of code where potential data races occur. Examine these locations carefully to ensure proper synchronization. Look for missing locks, incorrect lock usage, or other synchronization issues. |