Vector.size() returns -1???

Dec 2, 2011 at 12:43am
I have a bit of code like this.

1
2
3
4
5
6
while(myVector.size() > 0)
{
   int sz = myVector.size(); //This was for debugging

   //Do a bunch of stuff and push back the vector a number of times
}


sz is not changed by ANYTHING else in the program, and I have been getting a segfault in a VERY rare occurance later on in the program. When I inserted a breakpoint after the above code, I found out that,

sz = -1

How is this possible? Am I missing something?
Could it be because I may have tried to push back the vector past 0? But then why did the while loop even execute? I'm puzzled!
Dec 2, 2011 at 12:56am
Also, if it helps, i also had another debug variable. (This is a vector of ints)

int back = myVector.back()

and when debugged,

back = a really big random number.

this was the line that caused the segfault later on in the loop.

else if (owner == 0 && outStrings[i][myVector.back()] == 'S')
Last edited on Dec 2, 2011 at 12:57am
Dec 2, 2011 at 1:07am
size() returns an unsigned value so it can't return -1. size() probably return a very large value and that can't fit in the range of the signed int, so you get an overflow and the result is -1. This could be because you have added a huge number of elements to the vector (unlikely) or that you have used something like pop_back when the size was 0.
Dec 2, 2011 at 1:13am
Thanks peter that makes more sense!
Dec 2, 2011 at 6:57am
Try this:

1
2
cout << numeric_limits<unsigned int>::max() << "\n";
cout << (unsigned int) -1 << "\n";

Topic archived. No new replies allowed.