編譯帶有標誌的以下文件時,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++。
編譯帶有標誌的以下文件時,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++。
您可以使用靜態分析器,如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通過你的代碼僅成功地建造。
不在編譯時。儘管如此,你也許可以在運行時檢查它。
您可以std::vector
代替陣列。 Vector具有訪問器成員函數(std::vector::at
),它在運行時執行邊界檢查。
不幸的是編譯時檢查緩衝區溢出是一個非常難以解決的問題。它通常由完整的靜態分析工具處理。
我記得看到從FFMPEG或X264沿
行一個gcc或g ++警告消息「陣列的警告索引可以是出界」
http://gcc.gnu.org/ml/gcc/2000-07/msg01000.html
好像它可能由它在。
約束是,你有一個像你上面的例子。只要你有變量而不是文字,這是不可能的。除了可能在一個簡單的循環中。
[根據維基百科](https://en.wikipedia.org/wiki/AddressSanitizer),ffmpeg使用AddressSanitizer。可能是它的輸出。更多關於AddressSanitizer [在A到另一個Q中](// stackoverflow.com/a/17637383/2157640) – Palec 2017-05-30 21:08:42
對於原始數組,我不這麼認爲,因爲-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。,
`{boost,std :: tr1,std} :: array` has`at`以及。 – 2011-01-24 05:09:51
`-Wall -Wextra -ansi -pedantic`不會爲此程序生成警告:( – EnabrenTane 2011-01-24 04:29:56