且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-01 19:22:58

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

$ cppcheck --enable=all test.cpp检查 test.cpp...[test.cpp:6]:(样式)变量arr"未赋值[test.cpp:8]:(错误)数组 'arr[2]' 索引 4 超出范围

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

Is it possible to have g++ show an error when compiling the following file with some flag?

#include <iostream>
using namespace std;

int main()
{
   int arr[ 2 ];

   cout << arr[ 4 ] << endl;

   return 0;
}

I saw some things like gcc -Wall -O2 main.c which only works with C, not C++.

You can use a static analyser such as Cppcheck. When run on your above code:

$ cppcheck --enable=all test.cpp
Checking test.cpp...
[test.cpp:6]: (style) Variable 'arr' is not assigned a value
[test.cpp:8]: (error) Array 'arr[2]' index 4 out of bounds

You can integrate Cppcheck into your build procedure and consider your code built successfully only if Cppcheck passes.