Reputation: 33
I'm working in Visual Studio for a class project. Since I can no longer tell if I'm going crazy or not, this code runs and immediately results in an 'index out of bounds' error. There's no way that should happen in my mind.
int _tmain(int argc, _TCHAR* argv[]){
vector<int> points;
for(int i = 0; i < points.size() - 1; i++){
points[i+1] = 2;
return 0;
}
There are no values in the vector so the size comes back as 0 and we're checking then if i < -1. Is 0 < -1? No, it's not so the loop never runs and the program should return.
The exact warning I get is this:
I am compiling for debug mode so I guess my question is, first, am I missing something? If not, is this some kind of weird Visual Studio Debug feature?
Upvotes: 0
Views: 102
Reputation: 57688
You need to either reserve
a size for the vector, so it knows to have memory for you accesses; or use push_back
to put the items in the vector.
push_back
:vector<int> points;
const unsigned int maximum_points = 42;
for(int i = 0; i < maximum_points; i++)
{
points.push_back(2);
}
const unsigned int maximum_points = 42;
vector<int> points(maximum_points);
for(int i = 0; i < maximum_points; i++)
{
points[i] = 2;
}
Upvotes: 0
Reputation: 27
Instead of running a for loop for this like you are currently:
for(int i = 0; i < points.size() - 1; i++)
You might want to use an if statement first, and then nest the loop in that, like so:
if (points.size() >= 0)
for(int i = 0; i < points.size(); i++)
Upvotes: 0
Reputation: 726559
Here is the expression that causes the problem:
i < points.size() - 1
when you subtract 1
from an unsigned value of zero (points.size()
is size_t
, which is unsigned) you get a very large number. Switch to this condition to fix the problem:
i + 1 < points.size()
It is identical mathematically, but it will not produce a numeric overflow unless i
is at the max value of int
.
Upvotes: 6