[英]How can vector const_iterator go past vector end?
I have the following code in an application that threw an access violation exception: 我的应用程序中有以下代码引发了访问冲突异常:
size_t CConnectionsDoc::get_active_connections( std::vector<CString> &conn )
{
CString temp;
size_t cnt = 0;
conn.clear();
if( initialized ) {
for( std::vector<ACTIVE_CONNECTIONS>::const_iterator c_i = connections_vector.begin();
c_i != connections_vector.end(); c_i++ ) {
temp.Format( "%s:%d:%d:%lu", ( LPCTSTR )c_i->their_ip,
c_i->their_port, c_i->our_sd, c_i->their_pa );
conn.push_back( temp );
cnt++;
}
}
return cnt;
}
void CConnectionsDoc::update_connections( const uint sd )
{
std::vector<ACTIVE_CONNECTIONS>::iterator iter = connections_vector.begin();
while( iter != connections_vector.end() ) {
if( iter->our_sd == sd ) {
connections_vector.erase(iter);
break;
}
iter++;
}
}
typedef struct active_connections
{
CString their_ip;
unsigned int their_port;
unsigned int our_sd;
unsigned long their_pa;
} ACTIVE_CONNECTIONS;
example data
their_ip "192.168.1.125"
their_port 60849
our_sd 1096
their_pa 2097260736
This is a Visual Studio 2012 C++ app and from a debugging session using a dump file I found the following values: 这是一个Visual Studio 2012 C ++应用程序,通过使用转储文件的调试会话,我发现了以下值:
initialized=1
connections_vector size=8
connections_vector capacity=13
connections_vector entries 0-7 have valid data and debugger does not show any entries past element 7
cnt=13 at the time of the crash (odd it is the same size of the capacity)
conn size=13
conn capacity=13
std::vector conn has the 8 correct entries from the connections_vector plus 5 entries that look like valid data, but connections_vector.erase(it) was called in another function to remove disconnected entries prior to calling get_active_connections. std :: vector conn具有来自connections_vector的8个正确条目以及看起来像有效数据的5个条目,但是在调用get_active_connections之前,在另一个函数中调用connections_vector.erase(it)来删除断开连接的条目。
It appears that the const_iterator went beyond connections_vector.end() until it tried to access one element beyond the capacity of the connections_vector and crashed, but I don't see how that is possible. 似乎const_iterator超出了connections_vector.end()的范围,直到它尝试访问超出connections_vector容量的一个元素并崩溃了,但是我不知道这是怎么可能的。 Any ideas?
有任何想法吗? Thanks in advance.
提前致谢。
You tried to erase some of the objects from the same vector. 您试图删除同一矢量中的某些对象。 If you don't use erase remove idiom, data will not be cleaned up from vector.
如果您不使用擦除删除惯用语,则不会从矢量中清除数据。 On top of that you did erase operation inside a loop, so iterator is invalidated.
最重要的是,您在循环内执行了擦除操作,因此迭代器无效。 Please refer following more details
请参考以下更多详细信息
Iterator invalidation rules 迭代器失效规则
http://en.wikipedia.org/wiki/Erase –remove_idiom http://en.wikipedia.org/wiki/擦除–remove_idiom
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.