OSTEP:Memory API
OSTEP:Memory API
本篇对应 OSTEP Version 1.10 的 “Interlude: Memory API”。核心任务是把 C 中动态 memory 的 API 与 process address space 联系起来,并通过具体 bug 说明 allocation、lifetime 和 pointer ownership 的边界。
本篇讨论 UNIX systems 中的 memory-allocation interfaces。问题很直接:在 UNIX/C program 中,理解如何 allocate 和 manage memory,是构建 robust、reliable software 的关键;常用的 interfaces 是什么?哪些错误必须避免?
THE CRUX:HOW TO ALLOCATE AND MANAGE MEMORY
在 UNIX/C programs 中,如何正确地 allocate 和 manage memory?常用的 interfaces 是什么?哪些 mistakes 必须避免?
类型与定位
- 笔记类型:教程/实践
- 翻译基准:官方
vm-api.pdf,Version 1.10。 - 格式说明:代码示例保留 C 语法、API 名称和错误输出;源文档没有独立图片。
TL;DR
malloc()从 heap 请求一段 runtime memory,返回指向它的 pointer;free()结束这段 allocation 的 lifetime。sizeof()得到类型或对象所需的 byte 数;不要手写类型大小,也不要把sizeof(pointer)当成 pointed object 的大小。NULL表示 pointer 不指向有效 object;dereference NULL 是错误。- memory bug 的本质通常是 invalid lifetime:未初始化、越界、use-after-free、double-free 或 memory leak。
brk()/sbrk()是更底层的 heap boundary 接口,但实际 program 通常使用 allocator 提供的malloc()/free()。
目录
| 章节 | 内容 |
|---|---|
| Memory Types | stack、heap、static data |
| malloc | 请求动态 memory |
| free | 释放 allocation |
| 常见错误 | allocation/lifetime bugs |
| 底层接口 | brk 与 sbrk |
Memory Types
14.1 Types of Memory
C program 的 memory 大致包括:
- code:program instructions,通常只读;
- static data:global/static variables;
- stack:local variables、function parameters、return addresses,由 compiler 管理;
- heap:运行时动态申请和释放的 memory,由 programmer/allocator 管理。
stack memory 的 allocation 和 deallocation 由 compiler 隐式管理,因此也叫 automatic memory。例如,声明 int x 时,compiler 会在进入 func() 时为它在 stack 上留出空间,函数返回时自动回收;如果希望某条 information 在 function invocation 结束后继续存在,就不能把它只放在 stack 上。
void func() {
int x; // 在 stack 上声明一个 integer
...
}
heap memory 用于需要更长 lifetime 的数据,allocation 和 deallocation 必须由 programmer 显式完成,因此责任更重,也更容易产生 bug。下面一行代码同时涉及 stack 和 heap:compiler 先为 pointer x 在 stack 上留出空间,随后 malloc() 在 heap 上申请一个 integer,并把返回的 address 存到 stack 中的 x。
void func() {
int *x = (int *) malloc(sizeof(int));
/* x 本身在 stack;它指向的 integer 在 heap */
}
flowchart TD
AS[Process address space] --> C[Code]
AS --> D[Static data]
AS --> H[Heap: malloc/free]
AS --> S[Stack: calls/locals]
malloc()
14.2 The malloc() Call
malloc(size) 从 heap 请求 size bytes,并返回 void *。成功时得到一段可供 program 使用的 memory;失败时返回 NULL。返回 memory 的内容未初始化,读取其中的值是错误的。
使用 malloc() 需要包含 <stdlib.h>;prototype 是 void *malloc(size_t size)。参数 size_t 表示需要的 byte 数。通常不要直接写一个 magic number,而应使用 sizeof():它是一个 compile-time operator,不是 runtime function call。
double *d = (double *) malloc(sizeof(double));
malloc() 返回 void *,也就是一个不带具体类型的 address;C 允许 programmer 决定如何使用它。对返回值做 cast 主要是向 compiler 和读代码的人表明“我知道这个 address 的目标类型”,在 C 中并不是正确性所必需的。
int *x = malloc(sizeof(int));
if (x == NULL) {
// allocation failed
exit(1);
}
*x = 10;
使用 sizeof(int) 而不是猜测 int 的 byte 数;对 array 则使用 n * sizeof(*array),这样类型变化时更安全。
需要特别区分 pointer 本身的大小和它指向的 allocation 大小:
int *x = malloc(10 * sizeof(int));
printf("%zu\n", sizeof(x)); // pointer 的大小:常见为 4 或 8
int y[10];
printf("%zu\n", sizeof(y)); // compiler 能知道整个 array 的大小
对于 string,应该使用 malloc(strlen(s) + 1),额外的 1 用来保存结尾的 \0;直接使用 sizeof() 通常不能得到动态 string 所需的大小。
在 C 中,NULL 通常并不是特殊 object,而是表示零值的 macro,例如 #define NULL 0,有时也写作 #define NULL (void *)0。因此,NULL 只表示“没有有效指向”,不能对它进行 dereference。
TIP:WHEN IN DOUBT, TRY IT OUT
不确定某个 routine 或 operator 的行为时,除了阅读 manual page 和其他 documentation,没有什么能替代实际编写小程序并运行它。作者也正是通过实验确认
sizeof()在 pointer、array 等不同场景下的行为。
free()
14.3 The free() Call
free(ptr) 释放此前通过 malloc() 等 allocator API 获得的 allocation。释放后,该 memory 不再属于 program;继续 dereference ptr 是 use-after-free,再次 free(ptr) 是 double-free。
free() 只接收 pointer,不接收 allocation 的 size;因此 memory-allocation library 必须自己记录每个 allocation 的大小。传给 free() 的 pointer 必须是此前由 malloc()(或兼容 allocator API)返回的原始 pointer,不能是任意 address 或中间偏移量。
int *x = malloc(10 * sizeof(int));
if (x != NULL) {
free(x);
}
把 pointer 设为 NULL 可以降低误用同一 pointer 的风险,但它不会修复其他 aliases;真正的关键是明确 ownership 和 lifetime。
常见错误
14.4 Common Errors
| 错误 | 例子 | 后果 |
|---|---|---|
| 未初始化 pointer | int *p; *p = 1; | 写入未知地址 |
| NULL dereference | int *p = NULL; *p = 1; | invalid access/异常 |
| 越界 | a[n],但合法下标是 0..n-1 | 覆盖其他 memory |
| use-after-free | free(p); *p = 1; | 使用已结束 lifetime 的 object |
| double-free | 连续两次 free(p) | allocator metadata 损坏 |
| memory leak | 丢失唯一 pointer 后未 free() | allocation 永远无法回收 |
| 错误大小 | malloc(sizeof(p)) 而 p 是 pointer | 分配 pointer 大小,不是 object 大小 |
memory safety 不只取决于 API 调用是否成功,还取决于每个 pointer 所指 object 的 lifetime、边界和 ownership。
这些错误有一个共同特点:它们通常能够成功 compile,甚至能够运行一次或多次;compiler 没有义务替 programmer 检查动态 memory 的 lifetime。许多更新的 languages 通过 garbage collector 自动管理 object:programmer 仍然申请 object,但不必显式调用 free(),collector 会寻找已经没有 references 的 memory 并回收它。不过,即使使用 garbage-collected language,只要 program 仍保留一个不再需要的 reference,memory leak 仍然可能发生。
还有一些常见错误值得单独列出:
- 忘记 allocation:
char *dst; strcpy(dst, src);中dst没有指向已分配空间,通常会触发 segmentation fault;正确做法是按strlen(src) + 1分配,或使用strdup()。 - 分配不足:少分配一个 byte 的 string buffer 可能造成 buffer overflow。程序有时看似正常,有时覆盖无关数据,有时直接 crash;很多 security vulnerabilities 就来自这种越界 [W06]。
- 忘记初始化:
malloc()返回的 memory 未初始化,读取其中的 value 属于 uninitialized read,不能假定它是 zero。 - 过早释放:仍有 pointer 指向已释放 object 时,形成 dangling pointer;后续 allocation 可能复用那段 memory,让错误变得更加隐蔽。
- 错误释放:把非 allocator 返回的 pointer 传给
free(),行为未定义。
另外两类错误也需要单独注意:
- 重复释放:同一 allocation 被
free()多次,即 double free。其结果是 undefined behavior,allocator 可能陷入混乱、破坏自身 metadata,甚至直接 crash。 - 错误调用
free():free()只接受 allocator 之前返回的原始 pointer;不能传入 stack address、任意整数或 array 中间位置的 pointer。错误的 pointer 可能使 allocator 破坏无关 memory。
这些程序往往能够 compile,甚至能够运行一次或多次;“它之前运行过”并不等于它是正确的。Purify [HJ92] 和 Valgrind [SN05] 等工具可以帮助定位 memory leak、invalid access 和 undefined value。
TIP:IT COMPILED OR IT RAN ≠ IT IS CORRECT
compiler 能成功生成 executable,或 program 恰好运行成功,都不足以证明 C program 正确。memory layout、allocator 行为和时机的微小变化都可能使隐藏的 bug 暴露出来。
ASIDE:WHY NO MEMORY IS LEAKED ONCE YOUR PROCESS EXITS
memory management 有两个层次:OS 向 process 分配并在 process 退出时回收 pages;process 内部的 allocator 则在 heap 中管理
malloc()与free()。即使 program 忘记调用free(),OS 仍会在 process 结束时回收 code、stack 和 heap 的全部 pages。因此短命 process 不会产生跨 process 的永久 memory leak;但 long-running server、database 和 OS kernel 中的 leak 会持续积累并最终耗尽 memory。
短命 process 即使没有在退出前逐块调用 free(),OS 仍会在 process 结束时回收其所有 pages,包括 code、stack 和 heap;因此不会产生跨 process 的永久 memory leak。但这不是适合长期程序的习惯:long-running server 或 OS kernel 中的 leak 会持续积累,最终耗尽 memory。即使短程序可以依赖 process exit 的整体回收,也应养成释放显式 allocation 的习惯。
底层接口
14.5 Underlying OS Support
Unix allocator 通常从 OS 的 address space 获取 heap memory。brk() 和 sbrk() 可以调整 process 的 heap boundary;allocator 在其上实现更方便的 malloc()/free(),并负责复用、切分和合并 free blocks。
application 通常不应直接依赖 brk()/sbrk() 管理对象,因为它们只改变 heap 边界,不提供 object-level allocation、alignment、free-list 或 fragmentation 管理。
malloc() 和 free() 本身是 library calls,不是 system calls。allocator 在 process 的 virtual address space 内管理 heap,同时在需要更多 pages 时通过 system calls 向 OS 请求 memory。brk() 把 program break(heap 末端)设置为指定 address;sbrk() 则接收一个 increment,完成类似的调整。application 不应直接调用它们,否则很容易破坏 allocator 的内部状态。
另一个接口是 mmap();使用恰当参数时,它可以在 process 中创建 anonymous memory region。这个 region 不与某个 file 关联,而是与 swap space 相关,之后也可以像 heap 一样管理。
14.6 Other Calls
calloc() 会 allocation 并将 memory 清零;realloc() 可以为已有 object 创建更大的 region、复制旧内容并返回新 pointer。它们适合构建动态 vector,但仍必须正确管理返回 pointer、旧 region 的 lifetime 和 failure case。
对于 short-lived program,即使没有逐块调用 free(),process 退出时 OS 也会回收它的全部 pages(包括 code、stack 和 heap),所以不会产生跨 process 的永久 memory leak。但对 long-running server、database,尤其是 OS kernel,leak 会持续积累并最终耗尽 memory;养成释放自己显式 allocation 的习惯仍然重要。
14.7 Summary
本章介绍了 malloc()、free()、brk()、sbrk()、mmap()、calloc() 与 realloc() 等 memory-allocation interfaces;核心不是记住 API 名称,而是理解 object 的 allocation、lifetime、ownership 和正确释放边界。
实践检查清单
- allocation size 是否使用
sizeof(*ptr)或sizeof(type)? - 是否检查
malloc()的NULL返回值? - 每次 allocation 的 ownership 是谁?
- object 的 lifetime 何时开始、何时结束?
free()后是否还有 aliases 被使用?- array index 是否在边界内?
- 是否用工具检查 leak、越界和 use-after-free?
Homework(Code)
本练习先故意编写 buggy programs,再使用 debugger(例如 gdb)和 memory-bug detector(valgrind)定位问题。
- 编写
null.c:创建一个 integer pointer,将其设为NULL,然后尝试 dereference。编译为null并运行;会发生什么? - 使用
-g编译,把 symbol information 写入 executable;执行gdb ./null,进入 gdb 后输入run。debugger 会显示什么? - 使用
valgrind --leak-check=yes ./null运行该程序。memcheck输出了什么?如何解释它? - 编写一个使用
malloc()但在退出前忘记free()的程序。分别用 gdb 和valgrind --leak-check=yes检查它。 - 用
malloc创建一个名为data、大小为 100 的 integer array,然后执行data[100] = 0。直接运行和用 valgrind 运行分别会怎样?程序正确吗? - 创建并释放一个 integer array,然后尝试打印其中一个 element。程序能否运行?用 valgrind 时会发生什么?
- 将一个“有趣”的 value 传给
free(),例如前面分配的 array 中间位置的 pointer。会发生什么?是否需要工具才能发现这类问题? - 尝试其他 memory-allocation interfaces:实现一个 vector-like data structure,使用 array 存储 elements,并通过
realloc()在添加 entry 时扩大空间。它的性能如何?与 linked list 相比怎样?用 valgrind 查找 bug。 - 继续阅读 gdb 和 valgrind 的使用文档。熟悉 tools 对 UNIX/C environment 中的 debugging 至关重要。
与已有笔记的关系
- OSTEP 系列索引:本系列总目录。
- OSTEP:地址转换:malloc 得到的 pointer 属于 process 的 virtual address space。
- OSTEP:进程抽象:heap 与 stack 是 process machine state 的组成部分。
- OSTEP:地址转换:已有 Linux memory 管理视角的补充。
参考资料
References
| 标识 | 资料 |
|---|---|
[HJ92] | R. Hastings, B. Joyce, “Purify: Fast Detection of Memory Leaks and Access Errors”, USENIX Winter 1992。 |
[KR88] | Brian Kernighan, Dennis Ritchie, The C Programming Language, Prentice-Hall, 1988。 |
[N+07] | G. Novark, E. D. Berger, B. G. Zorn, “Exterminator: Automatically Correcting Memory Errors with High Probability”, PLDI 2007。 |
[SN05] | J. Seward, N. Nethercote, “Using Valgrind to Detect Undefined Value Errors with Bit-precision”, USENIX 2005。 |
[SR05] | W. Richard Stevens, Stephen A. Rago, Advanced Programming in the UNIX Environment, Addison-Wesley, 2005。 |
[W06] | T. Werthman, “Survey on Buffer Overflow Attacks and Countermeasures”, 2006。 |
原文 References 中的工具介绍和阅读建议在对应正文中保留;文献表只列出作者、题名、出处和用途。
原文逐段复核补充
- 官方 vm-api.pdf 为 Version 1.10,共 12 页;正文编号为 14.1–14.7,末尾为 9 道 Code Homework。原文没有独立图片;笔记中的 address-space Mermaid 图是帮助理解的语义补充,不对应原 PDF 图片。
- 已补回原文 stack
int x示例、heap 中int *x = (int *) malloc(sizeof(int))的 stack/heap 双重 allocation 解释、malloc()prototype、sizeof(pointer)与静态 array 的对比、strlen(s) + 1的 string 规则,以及free()只接收 allocator 返回 pointer 的约束。 - 已核对 common errors 的原文顺序:forgetting to allocate、not allocating enough、forgetting to initialize、forgetting to free、freeing before done、freeing repeatedly、calling
free()incorrectly;并保留 compiler 成功编译或 program 偶然运行不等于正确的主旨。 - 已核对 process-exit 时 OS 回收 code/stack/heap pages 的两层 memory-management 解释、
brk/sbrk的 program-break 语义、mmap()anonymous region、calloc()zeroing 和realloc()copy-to-larger-region 的说明。 - 原文脚注 ¹ 说明本章短而直接;脚注 ² 说明 C 中
NULL通常是零值 macro;脚注 ³ 解释 segmentation fault 的夸张措辞。脚注 ² 的技术内容已在malloc()小节中补明。
评论 (0)