浮点异常、分段错误和类似错误

Floating point exceptions,segmentation faults and similar errors

我有时会遇到此类错误。我的问题是,有没有办法找出有关此错误发生的时间和地点(哪一行)的信息?我在 ubuntu linux 14.04。使用 sublime 和 g++。

这是我当前的代码。我得到一个浮点异常。它需要 2 个向量并打印可被第一组的每个元素整除并且可以整除第二组的每个元素的数字。

发布代码与主题有点无关,但它迫使我找到一种合适的方法来调试提到的错误类型。第一次来这里提问,请放轻松

 int main()
{
    vector<int> firstVector;
vector<int> secondVector;
firstVector = {2,4};
secondVector = {16,32,96};
auto it = firstVector.begin();
for (int i = 1; i <= 100; ++i)
{
   it = firstVector.begin();
    for (; ; ++it)
    {
        if(i%(*it)!=0)
            break;
        if(it==firstVector.end())
        {
            it=secondVector.begin();
            while(it!=secondVector.end())
            {
                if((*it)%i!=0)
                {
                    it=firstVector.begin();
                    break;
                }
                it++;
            }
        }
        if(it==secondVector.end())
            break;
    }
    if(it==secondVector.end())
        cout << i << endl;
}
return 0;
}

我猜 firstVectorsecondVector 的迭代有问题。在第二个循环中:

 auto it = firstVector.begin();
 for (; ; ++it)
 {

itfirstVector 的迭代器。但是在下一个循环中:

 it=secondVector.begin();
 while(it!=secondVector.end())
 {

it 成为 secondVector 的迭代器。在此 while 循环之后,在外部 for 循环中继续迭代 it。在 .end() 元素处和之后递增 ++it 并访问元素 if(i%(*it)!=0)。这导致 UB:

This element acts as a placeholder; attempting to access it results in undefined behavior.

这个问题有两个问题。由于 Nikita 已经解决了您的代码...

My question is, is there a way to find out information about when and where(which line) exactly this error occurs?

使用 gdb name-of-executable 在 Linux 上进行调试。简单地 run 并且程序将在发生段错误时中断,或者我相信会抛出致命异常。它会告诉你文件名和行号。

您还可以查找更多 gdb 命令,如下所示:http://www.yolinux.com/TUTORIALS/GDB-Commands.html