[Found a doublicate here: C++ - detect out-of-range access ]
[在这里发现一个问题:C ++ - 检测超出范围的访问]
If I have a programm with "out of range vector access", like this:
如果我有一个“超出范围矢量访问”的程序,像这样:
std::vector<int> A(2);
...
A[10] = 3;
Do I have a way to find this error for sure? I mean something like compile in debug mode and see whether some assertion stops the execution.
我有办法确定找到这个错误吗?我的意思是在调试模式下编译,看看某些断言是否会停止执行。
Up to now I have checked it by my own. But may be I don't have to write additional code?
到目前为止,我已经自己查了一下。但可能是我不必编写额外的代码?
P.S. I checked assertion of course. It doesn't called.
附:我当然检查过断言。它没有打电话。
With this program:
有了这个程序:
#include <vector>
int main() {
std::vector<int> A(2);
A[10] = 3;
return 0;
}
compiled by
g++ 1.cpp -O0; ./a.out
So it looks like std doesn't have assertion in the code, I can't stop wonder why they don't make such a simple check.
所以看起来std在代码中没有断言,我不禁想知道为什么他们不做这么简单的检查。
2 个解决方案
#1
13
Use at()
member function:
在()成员函数使用:
std::vector<int> A(2);
A.at(10) = 3; //will throw std::out_of_range exception!
Since it may throw exception, you would like to catch it. So use try{} catch{}
block!
因为它可能会抛出异常,所以你想抓住它。所以使用try {} catch {}块!
Hope that helps.
希望有所帮助。
#2
1
Do I have a way to find this error for sure? I mean something like compile in debug mode and see whether some assertion stops the execution.
我有办法确定找到这个错误吗?我的意思是在调试模式下编译,看看某些断言是否会停止执行。
Valgrind easily catches these errors. Just run:
Valgrind很容易发现这些错误。赶紧跑:
valgrind ./YOUR_EXECUTABLE
I can't stop wonder why they don't make such a simple check.
我不禁想知道为什么他们不做这么简单的检查。
See this answer.
看到这个答案。
#1
13
Use at()
member function:
在()成员函数使用:
std::vector<int> A(2);
A.at(10) = 3; //will throw std::out_of_range exception!
Since it may throw exception, you would like to catch it. So use try{} catch{}
block!
因为它可能会抛出异常,所以你想抓住它。所以使用try {} catch {}块!
Hope that helps.
希望有所帮助。
#2
1
Do I have a way to find this error for sure? I mean something like compile in debug mode and see whether some assertion stops the execution.
我有办法确定找到这个错误吗?我的意思是在调试模式下编译,看看某些断言是否会停止执行。
Valgrind easily catches these errors. Just run:
Valgrind很容易发现这些错误。赶紧跑:
valgrind ./YOUR_EXECUTABLE
I can't stop wonder why they don't make such a simple check.
我不禁想知道为什么他们不做这么简单的检查。
See this answer.
看到这个答案。