Reputation: 24771
I have a vector<int>
called pitches
. I'm getting periodic bad access
on the last line below:
int play = 0;
bool didFind = 0;
vector<int>::const_iterator iterator;
for (iterator = pitches.begin(); iterator != pitches.end(); ++iterator) {
if (*iterator > lastpitch) { // lastpitch is an int
didFind = 1;
play = *iterator;
break;
}
}
if (!didFind) play = *(pitches.begin()); // this line gives me bad access
I had previously tried *pitches.begin()
on the last line but that always provided bad access and I understand that now. But while I get it less often now, this play=*(pitches.begin());
is still doing the same occasionally. I cannot see anything in the above that would cause that, any suggestions appreciated.
Upvotes: 0
Views: 647
Reputation: 2088
If pitches
vector has size 0
, the things inside
for (iterator=pitches.begin();iterator!=pitches.end();++iterator)
doesn't get executed and therefore didFind=0
.
The statement inside if
is evaluated. Yet pitches
is empty means pitches.begin()==pitches.end()
. Dereferencing a pitches.end()
is to access out of bound and therefore gives bad access
.
Upvotes: 4