0

While trying to randomly access an empty vector in c++, there is segmentation fault.

vector<int> g;
cout<<g[3];  //Segmentation fault

But if we do a single push_back() operation, then we can do random access there is no error:

vector<int> g;
g.push_back(1);
cout<<g[0]; //output = 1
cout<<g[3]; //output = 0

What is the reason behind this??

  • 2
    If i remember correctly, vectors allocate memory in chunks. You probably can't access a higher index. Regardless, this behavior is undefined – Easton Bornemeier Aug 08 '18 at 15:51
  • When first working with vectors (or even other containers) use `at` instead of `[]` at first. `at` will catch when you go out of bounds and throw an exception. – NathanOliver Aug 08 '18 at 15:51
  • 1
    @NathanOliver: Although, that's at some cost, which can be material especially when working through linear algebra calculations. – Bathsheba Aug 08 '18 at 15:52
  • *But if we do a single push_back() operation, then we can do random access there is no error:* -- There is an error -- you chose an element that is outside the bounds of the vector. What is the visible results of that error is a different story. – PaulMcKenzie Aug 08 '18 at 15:55
  • @Bathsheba True but when you first start learning about vector I would think safety should trump speed, at least until you get the hang of it. – NathanOliver Aug 08 '18 at 15:55
  • You are accessing out of bounds. This is Undefined Behaviour. You broke the rules of the language and *any* result is possible. Don't do that. – Jesper Juhl Aug 08 '18 at 16:11
  • Undefined behavior means only that the language definition does not tell you what the code should do. It does not mean that something bad will happen, although that's often the result. – Pete Becker Aug 08 '18 at 16:13
  • 2
    @PeteBecker I categorise *silently continuing with garbage* as "something bad". **Much worse** than terminating unexpectedly – Caleth Aug 08 '18 at 16:22

1 Answers1

4

The behaviour on attempting to acquire an element of a std::vector that's outside the bounds of that vector is undefined. Don't do it, and don't rely on any behaviour.

Perhaps your push_back causes std::vector to grab more memory than it needs as a guard against frequent reallocation and memory defragmentation?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483