简体   繁体   中英

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:

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.

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM