C++不给出越界错误.有没有办法强制编译器检查而不是未定义的行为?

C++ not giving out of bounds error. Is there a way to force the compiler to check instead of undefined behavior?

本文关键字:检查 未定义 编译器 越界 错误 有没有 C++      更新时间:2023-10-16

我没有收到任何边界错误或分割错误,我确实从人们的评论中看到这很常见。但是有没有办法让编译器发出错误,而不是打开我的程序以可能出现未定义的行为?

#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 指针或完全超出程序内存区域的内容。