Accessing empty vector will always throw exception?

23 07 2008

Vectors are cool! if we access out of array, they will throw unhandled exception. I used to get a lot. 🙂

But are you sure that you’re vector always throw exception if you access out of array?

Answer is NO. Well have a look at the code snippet. At first we access an empty vector which throws an exception. Then we insert some values and then clear the vector to make it empty. Then if we access the empty vector, it won’t throw exception! Have a look at it.

// This class is just to access the protected members
// of vector.
class IntVector : vector<int>
    friend void CheckVector();

void CheckVector()
    IntVector IntArray;

        // Try to access element which result in exception.
        int Value = IntArray[ 0 ];
    catch( ... )
        // It will reach here since we're trying
        // to access an empty vector.

    // Now add one value and clear the vector.
    IntArray.push_back( 10 );

        // Now try to access element. You can access it
        // eventhough the vector is empty.
        int Value = IntArray[ 0 ];
    catch( ... )
        // It will not reach here.

    // Check the size of memory allocation inside vector.
    int InternalSize = _msize( IntArray._First );
    int VectorSize = IntArray.size();

Well, the reason is optimization. While clearing the vector, for optimization it won’t removes the allocated memory. It just sets the size as 0. So if you access the data by using array operator, you’ll get old value.

The morel is always check the size of array before accessing it. Well the behavior is observed in Visual Studio 6.0. Different IDEs and platforms may show different behavior. Take care!

Targeted Audience – Intermediate.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: