Shibli
Shibli

Reputation: 6139

Vector going out of bounds without giving error

I have a std::vector. I check its size which is 6 but when I try to access vec[6] to check whether it will give error, I get no error but some number instead. Should not it give an error?

edit: something like:

struct Element
{
    std::vector<double> face;
};

int main()
{
    Element elm;

    .... // insert 6 elements into elm.face

    std::cout << elm.face.size() << std::endl; // answer is 6
    std::cout << elm.face[6] << std::endl; // answer is some number
}

Upvotes: 34

Views: 30653

Answers (4)

john smith
john smith

Reputation: 185

Data structures are indexed starting at 0, so if you are accessing vec[6], then this is going to be out of bounds. You are likely not getting an error due to a memory issue; there could be something there from previous code you have run, or some similar error.

Upvotes: -4

kgraney
kgraney

Reputation: 2051

std::vector performs bounds checking when the at() member function is used, but it does not perform any checks with operator[].

When out of bounds operator[] produces undefined results.

Upvotes: 66

Willem Hengeveld
Willem Hengeveld

Reputation: 2776

As stated in kgraney's answer, this is undefined behaviour. However, most c++ libraries have some facility to abort, or raise an exception in such cases. Usually controlled by setting or unsetting specific compiler macro's.

I have made an overview of the relevant documentation:

gnu libstdc++

clang libcxx

boost

Microsoft

Note that gnu and clang disable the checks by default, while microsoft has them enabled by default. If you are unaware of this, your code may run significantly slower in debug mode on a microsoft system.

Upvotes: 13

icktoofay
icktoofay

Reputation: 129001

It's undefined behavior. Undefined behavior does not necessarily mean you'll get an error: you might, but you might instead get some result that doesn't make much sense.

Upvotes: 4

Related Questions