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