说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C3-C_debug/index.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
3. C Debugging Tools
本节介绍两个调试工具:GNU 调试器 GDB,它可以用来检查程序的运行时状态;以及 Valgrind(读作 “Val-grinned”),一套流行的代码剖析工具。具体来说,我们介绍 Valgrind 的 Memcheck 工具,它分析程序的内存访问,检测无效的内存使用、对未初始化内存的使用以及内存泄漏。
In this section, we introduce two debugging tools: the GNU debugger (GDB), which is useful for examining a program’s runtime state, and Valgrind (pronounced “Val-grinned”), a popular code profiling suite. Specifically, we introduce Valgrind’s Memcheck tool, which analyzes a program’s memory accesses to detect invalid memory usage, uninitialized memory usage, and memory leaks.
现代更新(截至 2026-11)· 在 Apple Silicon Mac 上用什么
本章的两个工具在 Apple Silicon(ARM64)Mac 上都不能直接使用:
- Valgrind:官方支持列表中,macOS(Darwin)只有 X86/AMD64 版本,且只到 macOS 13;ARM64 只支持 Linux、FreeBSD 和 Android。最新版本是 2026 年 10 月发布的 3.28.0。Valgrind 支持平台 · Valgrind NEWS
- GDB:macOS 上的标准调试器是随 Xcode 命令行工具提供的 LLDB,LLVM 官方维护着一份 GDB 命令与 LLDB 命令的对照表,本章的
break、run、next、print、bt等命令基本都有一一对应的写法。GDB to LLDB command map
想原样跟做本章,最省事的办法是在 Linux 虚拟机或容器(ARM64 Linux 即可)里运行 GDB 和 Valgrind;只想检查内存错误的话,也可以在 macOS 上用 Clang 的 -fsanitize=address。
GDB 一节包含两个 GDB 会话示例,演示查找程序缺陷时常用的 GDB 命令。我们还会讨论 GDB 的一些高级特性,包括把 GDB 附加到正在运行的进程、GDB 与 Makefile、GDB 中的信号控制、在汇编代码层面调试,以及调试多线程 Pthreads 程序。
The GDB section includes two sample GDB sessions that illustrate commonly used GDB commands for finding bugs in programs. We also discuss some advanced GDB features, including attaching GDB to a running process, GDB and Makefiles, signal control in GDB, debugging at the assembly code level, and debugging multithreaded Pthreads programs.
Valgrind 一节讨论内存访问错误,以及它们为何如此难以发现。其中还包括一个对含有若干内存访问错误的程序运行 Memcheck 的例子。Valgrind 套件中还有其他程序剖析和调试工具,我们会在后面的章节中介绍。例如,第 11 章介绍缓存剖析工具 Cachegrind,第 12 章介绍函数调用剖析工具 Callgrind。
The Valgrind section discusses memory access errors and why they can be so difficult to detect. It also includes an example run of Memcheck on a program with some bad memory access errors. The Valgrind suite includes other program profiling and debugging tools, which we cover in later chapters. For example, we cover the cache profiling tool Cachegrind in Chapter 11, and the function call profiling tool Callgrind in Chapter 12.