Quick Reference
| Topic | File |
|---|
| malloc/free, leaks, double free | INLINECODE0 |
| Null, dangling, pointer arithmetic |
pointers.md |
| Null terminator, buffer overflow |
strings.md |
| Integer overflow, signed/unsigned |
types.md |
| Macro traps, include guards |
preprocessor.md |
| Common undefined behavior |
undefined.md |
Critical Rules
- -
malloc returns void* — cast required in C++, optional in C but check for NULL - INLINECODE8 — always null after free to prevent double-free
- INLINECODE9 in function gives pointer size, not array size — pass length separately
- INLINECODE10 — no room for null terminator, UB when used as string
- INLINECODE11 doesn't check bounds — use
strncpy and manually null-terminate - Signed overflow is UB — compiler can optimize assuming it never happens
- INLINECODE13 is UB — no sequence point between modifications
- Returning pointer to local variable — dangling pointer, UB on use
- INLINECODE14 —
SQUARE(1+2) = 1+2*1+2 = 5, not 9 - INLINECODE17 with overlapping regions — use
memmove instead - Uninitialized variables — contain garbage, UB if used
- Array out of bounds — no runtime check, silent corruption or crash
快速参考
| 主题 | 文件 |
|---|
| malloc/free、内存泄漏、双重释放 | memory.md |
| 空指针、悬空指针、指针运算 |
pointers.md |
| 空终止符、缓冲区溢出 | strings.md |
| 整数溢出、有符号/无符号 | types.md |
| 宏陷阱、包含守卫 | preprocessor.md |
| 常见未定义行为 | undefined.md |
关键规则
- - malloc 返回 void — 在 C++ 中需要强制类型转换,在 C 中可选但需检查是否为 NULL
- free(ptr); ptr = NULL; — 释放后始终置空,防止双重释放
- 函数中的 sizeof(array) 返回指针大小而非数组大小 — 需单独传递长度
- char str[5] = hello; — 没有空间存放空终止符,作为字符串使用时为未定义行为
- strcpy 不检查边界 — 应使用 strncpy 并手动添加空终止符
- 有符号整数溢出是未定义行为 — 编译器可能假设其不会发生而进行优化
- i++ + i++ 是未定义行为 — 两次修改之间没有序列点
- 返回指向局部变量的指针 — 产生悬空指针,使用时为未定义行为
- #define SQUARE(x) xx — SQUARE(1+2) = 1+2*1+2 = 5,而非 9
- 对重叠区域使用 memcpy — 应改用 memmove
- 未初始化的变量 — 包含垃圾值,使用时为未定义行为
- 数组越界 — 无运行时检查,导致静默数据损坏或崩溃