我在VS2008 C ++ vector中发现了一个错误吗? [英] Did I get bit my a bug in VS2008 C++ vector?

查看:78
本文介绍了我在VS2008 C ++ vector中发现了一个错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个应用程序突然抛出了一个异常.幸运的是,它是在调试版本中发生的,因此我能够查看到底发生了什么.引发的异常是向量下标超出范围".我检查了引发此异常的代码,这对我来说没有任何意义.希望有人可以向我解释它,或者让我知道这是否实际上是C ++向量类中的错误.

这是引发异常的代码(来自C:\ Program Files(x86)\ Microsoft Visual Studio 9.0 \ VC \ include \ vector行773):

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



如果"if(size()< = _Pos)",换句话说,如果_Pos小于项目数,则抛出该异常.在这种情况下,_Pos的值为42,并且size()返回4097.
我不知道为什么_Pos必须大于size()才能运行此代码.在我看来,这似乎是Vector中的错误.

干杯,
理查德.



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.

推荐答案

好吧,我刚刚意识到我误解了size()< = _Pos.通常会抛出_Pos大于size()的情况.但是在这种情况下,_Pos WASN''T大于size(),因此它不应该引发异常.可能是线程问题,然后...
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...


首先,我发现了VS2008 vector的一些问题,但这不是其中的1个.

您的代码几乎可以肯定会出现此错误,您需要检查调用堆栈,并检查要在何处调用数组运算符以及_Pos的值.在您发布的功能中.

这是因为您尝试访问不存在的元素.
即向量中有3个元素,而您正尝试访问第4个元素(索引3)

C ++中的所有数组索引都从0开始,因此索引3实际上是元素4.
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.


这篇关于我在VS2008 C ++ vector中发现了一个错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆