Floating point exceptions,segmentation faults and similar errors

764 views Asked by At

I sometimes get this type of errors. My question is, is there a way to find out information about when and where(which line) exactly this error occurs? I'm on ubuntu linux 14.04. Using sublime and g++.

Here is my current code. I get a floating point exception in this. It takes 2 vectors and prints the numbers that are divisible by every element of the first set and can divide every element of the second set.

Posting the code is kinda irrelavant to the topic but it forced me to find a decent way to debug the mentioned error types.

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;
}
2

There are 2 answers

3
Nikita On BEST ANSWER

I guess there is a problem in iteration over firstVector and secondVector. In second loop:

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

it is iterator for firstVector. But in the next loop:

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

it becomes iterator for the secondVector. Iteration over it continues in the outer for loop after this while loop. You increment ++it and access elements if(i%(*it)!=0) at and after the .end() element. This leads to UB:

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

1
Keith M On

This question is kind of a two-parter. Since Nikita already addressed your code...

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

Use gdb name-of-executable to debug on Linux. Simply run and the program will break when a seg fault occurs or, I believe, a fatal exception is thrown. It will tell you the file name and line number.

You can also look up more gdb commands, like here: http://www.yolinux.com/TUTORIALS/GDB-Commands.html