C++不给出越界错误.有没有办法强制编译器检查而不是未定义的行为?
C++ not giving out of bounds error. Is there a way to force the compiler to check instead of undefined behavior?
我没有收到任何边界错误或分割错误,我确实从人们的评论中看到这很常见。但是有没有办法让编译器发出错误,而不是打开我的程序以可能出现未定义的行为?
#include <iostream>
#define MAX 10
int main(void){
int A[MAX] = {9, 3, 9, 3, 9, 3, 0, 0, 9, 3};
int C[10];
int B[MAX] = {0};
for (int i = 0; i < 10; i++) C[i] = 0;
// increment count of buckets containing this digit accordingly
for (int i = 0; i < MAX; i++) C[A[i]] = C[A[i]] + 1;
// count all count <= the current bucket to determine the correct index
for (int i = 1; i < 10; i++) C[i] = C[i] + C[i-1];
// copy the correct array element to output array B and decrement C array accordingly
for (int i = MAX-1; i >= 0; i--){
B[C[A[i]]] = A[i];
C[A[i]] = C[A[i]]-1;
}
std::cout << "nSorted array = ";
for (int i = 1; i <= MAX; i++) std::cout << " " << B[i] << " ";
std::cout << "n";
return 0;
}
没有人保证每次越界访问数组时都会得到SegFault
。某些数据结构会给你一个例外(例如 std::vector(,如果你尝试v.at(MAX)
.
尽管如此,您的程序通常具有大量内存,访问v[MAX]
只是访问下一个变量,例如,这是众所周知的技巧:
int a[10], b[10], c[10];
for( int i=0; i<30; i++) a[i] = 0; // zero THEM ALL
要可靠地获得SegFault
,您必须访问 NULL 指针或完全超出程序内存区域的内容。
相关文章:
- 编译C++时未定义的引用
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 不知道某个东西是否被忽略会引入未定义的行为吗
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- c++11评估顺序(未定义的行为)
- 使用mysql c++连接器的未定义引用
- 从python调用openMP共享库时,未定义opnMP函数
- 在 Mac 上使用 CMAKE 将 FFTW 和 FFTWPP 链接到项目中时未定义的符号
- 未定义的类模板不会实例化以检查友元函数
- boost::any 如何检查空值/未定义的值
- C++ 如何检查 char 变量是否未定义(未初始化)
- C++不给出越界错误.有没有办法强制编译器检查而不是未定义的行为?
- 类型特征检查 CRTP 派生,在基类中,问题是未定义的类型
- 未定义行为:代码审查的检查表
- Qt复选框/工具按钮,带有自定义/不同的检查/未选中的图标