C语言:gcc 或 g++ 数组边界检查方法
在 GCC 或 G++ 中,默认情况下不提供数组边界检查,但可以通过以下方法实现运行时检查:
1. 使用 AddressSanitizer (ASan)
AddressSanitizer 是 GCC 和 Clang 支持的动态内存错误检测工具,可以检测数组越界访问。编译时添加 -fsanitize=address
选项即可启用:
g++ -fsanitize=address -g -o your_program your_source.cpp
特点:
- 在运行时检测数组越界(堆、栈、全局数组均有效)。
- 错误发生时,会打印详细的错误信息(如越界位置、内存布局)。
- 对性能有一定影响(通常 2x 左右),适合调试环境。
示例:
int main() {int arr[5] = {0};arr[5] = 10; // 越界访问return 0;
}
运行后会输出类似:
ERROR: AddressSanitizer: stack-buffer-overflow
2. 使用 -fstack-protector
GCC 的栈保护选项(-fstack-protector
)可以检测栈缓冲区溢出,但主要用于防御攻击,不是专门的数组边界检查工具:
g++ -fstack-protector -o your_program your_source.cpp
3. 静态代码分析(编译时警告)
通过 -Wall -Wextra
开启警告,某些明显的越界访问可能在编译时被检测到:
g++ -Wall -Wextra -o your_program your_source.cpp
4. C++ 容器替代原生数组
使用 std::vector
或 std::array
的 .at()
方法,会在越界时抛出 std::out_of_range
异常:
#include <vector>
int main() {std::vector<int> vec(5);vec.at(5) = 10; // 抛出异常return 0;
}
总结
方法 | 原理 | 适用场景 | 性能影响 |
---|---|---|---|
AddressSanitizer | 运行时检测 | 调试/测试 | 较高 |
-fstack-protector | 栈保护 | 生产环境安全 | 低 |
静态分析警告 | 编译时检查 | 开发阶段 | 无 |
C++ 容器 .at() | 语言层面检查 | 所有场景 | 轻微 |
建议:开发阶段使用 AddressSanitizer 调试内存错误,生产环境优先选择安全的容器(如 std::vector
)。
编写 tri_yanghui.c 如下
/* tri_yanghui.c 计算杨辉三角 */
#include <stdio.h>
#include <stdlib.h>
#define N 21int a[N][N];int main(){int n;scanf("%d", &n);// 赋初值for(int i=1; i<=n; i++)a[i][1] = a[i][i] = 1;// 递归求二项式系数for(int i=1; i<=n; i++){for(int j=2; j<i; j++)a[i][j] = a[i-1][j] + a[i-1][j-1];}// 输出结果for(int i=1; i<=n; i++){for(int j=1; j<=i; j++)printf("%d ", a[i][j]);printf("\n");}
}
where tcc
D:\Tcc\tcc\tcc.exe
编译 tcc -b tri_yanghui.c
执行 .\tri_yanghui
25