2011-01-24 66 views
14

编译带有标志的以下文件时,g ++是否可能显示错误?是否可以在g ++中启用数组边界检查?

#include <iostream> 
using namespace std; 

int main() 
{ 
    int arr[ 2 ]; 

    cout << arr[ 4 ] << endl; 

    return 0; 
} 

我看到一些像gcc -Wall -O2 main.c这样的东西只能用于C而不是C++。

+1

`-Wall -Wextra -ansi -pedantic`不会为此程序生成警告:( – EnabrenTane 2011-01-24 04:29:56

回答

3

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

 
$ 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 

可以Cppcheck集成到您的构建过程,并考虑是否Cppcheck通过你的代码仅成功地建造。

0

您可以std::vector代替阵列。 Vector具有访问器成员函数(std::vector::at),它在运行时执行边界检查。

不幸的是编译时检查缓冲区溢出是一个非常难以解决的问题。它通常由完整的静态分析工具处理。

2

我记得看到从FFMPEG或X264沿

行一个gcc或g ++警告消息“阵列的警告索引可以是出界”

http://gcc.gnu.org/ml/gcc/2000-07/msg01000.html

好像它可能由它在。

约束是,你有一个像你上面的例子。只要你有变量而不是文字,这是不可能的。除了可能在一个简单的循环中。

+0

[根据维基百科](https://en.wikipedia.org/wiki/AddressSanitizer),ffmpeg使用AddressSanitizer。可能是它的输出。更多关于AddressSanitizer [在A到另一个Q中](// stackoverflow.com/a/17637383/2157640) – Palec 2017-05-30 21:08:42

3

对于原始数组,我不这么认为,因为-fbounds-check没有你的榜样和MinGW G ++ 4.4.1工作,因为旧的3.x的文档我不得不说

-fbounds -check

对于支持它的前端, 产生额外的代码来检查用于访问阵列 指数是 声明的范围内。这是 目前仅受Java 和Fortran 77前端支持,其中此 选项分别默认为true和false 。

然而,随着std::vector可以使用at有一个稍微不切实际的运行时间边界检查(产生异常)。并且您可以使用标准库的特殊调试版本,该版本可为[]提供实际的运行时间边界检查。例如,编译时......

#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{ 
    vector<int> arr(2); 

    cout << arr[ 4 ] << endl; 
} 

&hellip;你得到的G ++标准库的发布实施和调试版本不同分别不检查和检查行为:

 
C:\test> g++ x.cpp & a 
4083049 

C:\test> g++ x.cpp -D _GLIBCXX_DEBUG -D _GLIBCXX_DEBUG_PEDANTIC & a 
c:\program files\mingw\bin\../lib/gcc/mingw32/4.4.1/include/c++/debug/vector:265: 
    error: attempt to subscript container with out-of-bounds index 4, but 
    container only holds 2 elements. 

Objects involved in the operation: 
sequence "this" @ 0x0x22ff1c { 
    type = NSt7__debug6vectorIiSaIiEEE; 
} 

This application has requested the Runtime to terminate it in an unusual way. 
Please contact the application's support team for more information. 

C:\test> _ 

据传为新的G ++版本(4.0以后),你不需要_GLIBCXX_DEBUG_PEDANTIC符号。有关详细信息,请参阅GNU documentation

干杯& hth。,

+2

`{boost,std :: tr1,std} :: array` has`at`以及。 – 2011-01-24 05:09:51

相关问题