user818794
user818794

Reputation: 73

C++ vector strange behaviour

Consider this program:

#include <iostream>
#include <vector>

using namespace std;

int main(void)
{
    vector<double> a;
    while (a.size() <= 10)
        a.push_back(2);
    cout << a[15] << endl;
}

I would expect it to crash when asked to access 15-th element of a, but it does not (outputs 0 on my system). What gives? Is this some new feature in gcc or something?

Upvotes: 0

Views: 197

Answers (6)

andrea.marangoni
andrea.marangoni

Reputation: 1499

it is not strange..a vector grows it's size when it is inserted a.size()-1 element..so now you have kind of 20 elements.. (maybe not 20 but more than 11 (= )

Upvotes: 0

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

This references says that it

Returns a reference to the element at position n in the vector container.

A similar member function, vector::at, has the same behavior as this operator function, except that vector::at signals if the requested position is out of range by throwing an exception.

So, this might or might not crash.

Upvotes: 1

graham.reeds
graham.reeds

Reputation: 16476

Because the growth of the vector could be larger than 15 when you access it?

Check the capacity().

Upvotes: 0

Mario Corchero
Mario Corchero

Reputation: 5565

I the memory you are reading is inside your program it won't crash, c++ does not bounds checking

Upvotes: -1

Naveen
Naveen

Reputation: 73433

You are accessing an invalid memory location which leads to undefined behavior. So anything might happen.

Upvotes: 3

Nim
Nim

Reputation: 33655

the operator[] does no bounds checking, and in this case you were *un*lucky and the address at that location could be read without causing a run-time error.

Upvotes: 0

Related Questions