# AddressSanitizer 使用指南 ## 📋 概述 AddressSanitizer (ASan) 是一个快速的内存错误检测工具,可以检测: - 堆缓冲区溢出/下溢 - 栈缓冲区溢出/下溢 - 全局缓冲区溢出/下溢 - 释放后使用(Use-after-free) - 返回后使用(Use-after-return) - 重复释放(Double-free) - 内存泄漏 --- ## 🚀 快速开始 ### Windows (MSVC) ```powershell # 启用 AddressSanitizer php bin/compiler.php your-app.php --sanitize=address # 或简写 php bin/compiler.php your-app.php --sanitize=addr ``` **要求:** - Visual Studio 2019 16.9+ 或 Visual Studio 2022 - MSVC 编译器版本 19.29+ ### Linux/macOS (GCC/Clang) ```bash # 单个 sanitizer php bin/compiler.php your-app.php --sanitize=address # 多个 sanitizer(用逗号分隔) php bin/compiler.php your-app.php --sanitize=address,undefined # 可用的 sanitizer 类型: # - address: 地址错误检测 # - undefined: 未定义行为检测 # - thread: 线程竞争检测 # - memory: 未初始化内存读取检测 # - leak: 内存泄漏检测 ``` --- ## 🔍 示例输出 当检测到内存错误时,AddressSanitizer 会输出详细的错误信息: ``` ================================================================= ==12345==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000010 READ of size 4 at 0x602000000010 thread T0 #0 0x7ff6abc12345 in main D:\workspace\compiler\examples\test.php:10 #1 0x7ff6abc67890 in __scrt_common_main_seh 0x602000000010 is located 0 bytes to the right of 16-byte region [0x602000000000,0x602000000010) allocated by thread T0 here: #0 0x7ff6abc98765 in operator new[] #1 0x7ff6abc12340 in main D:\workspace\compiler\examples\test.php:8 SUMMARY: AddressSanitizer: heap-buffer-overflow ================================================================= ``` --- ## 💡 使用建议 ### 1. 开发阶段启用 在开发和测试阶段启用 AddressSanitizer,可以帮助您尽早发现内存错误: ```powershell # 编译带 AddressSanitizer 的版本 php bin/compiler.php debug-test.php --sanitize=address --no-console # 运行测试 .\debug-test.exe ``` ### 2. 不要与优化同时使用 AddressSanitizer 会降低程序性能(约 2x),建议: - 开发时:`-O0 --sanitize=address` - 发布时:`-O2`(不使用 sanitizer) ### 3. 结合调试信息使用 ```powershell # 同时启用调试信息和 AddressSanitizer php bin/compiler.php app.php --debug-info --sanitize=address ``` 这样可以在错误报告中看到源代码行号。 --- ## 🛠️ 常见用例 ### 检测数组越界 ```php