Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
One of my applications just threw an exception out of the blue. Luckily it happened in a debug build, so I was able to check out what exactly happened. The exception that was thrown is "vector subscript out of range". I checked the code that threw this exception, and it just doesn't make any sense to me. Hopefully someone can either explain it to me, or let me know if this is actually a bug in the C++ vector class.

Here's the code that threw the exception (from C:\Program Files(x86)\Microsoft Visual Studio 9.0\VC\include\vector line 773):
reference operator[](size_type _Pos)
		{	// subscript mutable sequence

 #if _HAS_ITERATOR_DEBUGGING
		if (size() <= _Pos)
			{
			_DEBUG_ERROR("vector subscript out of range");
			_SCL_SECURE_OUT_OF_RANGE;
			}
 #endif /* _HAS_ITERATOR_DEBUGGING */
		_SCL_SECURE_VALIDATE_RANGE(_Pos < size());

		return (*(_Myfirst + _Pos));
		}


The exception is thrown when 'if (size() <= _Pos)', in other words, if _Pos is smaller than the number of items. In this case, _Pos had a value of 42 and size() returns 4097.

I can't figure out why _Pos would need to be larger than size() for this code to work. To me, this seems like a bug in the Vector.

Cheers,
Richard.
Posted

Okay I just realized that I misinterpreted size() <= _Pos. It would normally throw is _Pos is larger than size(). But in this case, _Pos WASN'T larger than size() so it shouldn't have thrown the exception. Probably a threading issue, then...
 
Share this answer
 
Comments
Andrew Brock 3-Feb-11 5:46am    
If you are using the vector (or any data structure) from multiple threads, you MUST use a Mutex (http://msdn.microsoft.com/en-us/library/ms684266(v=vs.85).aspx) to ensure only 1 thread is accessing it at 1 time.

Note that you can read from it at as many times as you want but if something is modifying the vector nothing can read from it.
Firstly, I have found a few issues with the VS2008 vector, but this is not 1 of them.

This error is almost certainly with your code, you need to check the call stack and check where you are calling the array operator and the value of _Pos. in the function you posted.

This is because you are trying to access an element that does not exist.
i.e. there is 3 elements in the vector and you are trying to access the 4th element (index 3)

All array indices in C++ start at 0, so index 3 is actually element 4.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900