是否可以在g ++中启用数组边界检查?

827*_*827 15 c++ g++

在使用某个标志编译以下文件时,是否可能让g ++显示错误?

#include <iostream>
using namespace std;

int main()
{
   int arr[ 2 ];

   cout << arr[ 4 ] << endl;

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我看到了一些gcc -Wall -O2 main.c只适用于C而不是C++的东西.

vmp*_*str 7

不是在编译时.您可以在运行时检查它.

为此,请看一下: 使用g ++检查运行时数组边界


Gre*_*ill 5

您可以使用静态分析器,例如Cppcheck。在上面的代码上运行时:

$ cppcheck --enable=all test.cpp
正在检查 test.cpp...
[test.cpp:6]: (style) 变量 'arr' 未赋值
[test.cpp:8]: (error) 数组 'arr[2]' 索引 4 越界

您可以将 Cppcheck 集成到您的构建过程中,并仅在 Cppcheck 通过时才认为您的代码构建成功。