考虑这段代码
#include <vector>
#include <iostream>
main()
{
std::vector <int> x(1);
for(int q=0;; q++)
{
int y = x[q];
std::cout << q << " ";
}
}
在我使用 g++ 的系统上,在因段错误(核心转储)
崩溃之前最多会打印 32570。据推测,之所以需要这么长时间,是因为 ~32570 是操作系统和/或分配器将分配给 vector 的最小内存块的大小。但是当然,任何时候我们在数组末尾执行这样的操作通常都是一个错误。因此,如果我能让程序在发生这种情况时退出并显示有用的错误消息,那就太好了。
几年前,我记得使用 Xcode 时,它会以 std::vector
的类型(和名称?)退出。目前我在 Linux 上使用 g++。是否有任何解决方案(或其他)?
最佳答案
使用-D_GLIBCXX_DEBUG
编译为enable debug mode in STL containers .
或者,您也可以使用位于 __gnu_debug
namespace 中的特定调试容器。 ,例如__gnu_debug::vector
:
#include <iostream>
#include <debug/vector>
int main()
{
__gnu_debug::vector <int> x(1);
for(int q = 0; ; q++)
{
int y = x[q];
std::cout << q << " ";
}
}
关于c++ - 是否可以进行编译,以便错误的 std::vector 访问调用将退出程序,并显示有用的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36172617/