3

I notice that if I do vec[0] = 1 with a fresh empty std::vector<int>, vec.size() remains 0.

However I can then still do vec[0] to retrieve my 1.

Is this in the realm of undefined behavior? What is going on here? Is this simply writing the 1 into reserved memory space, and I should expect this to blow up in my face, right?

Steven Lu
  • 41,389
  • 58
  • 210
  • 364

2 Answers2

8

It is indeed Undefined behavior

[] Does not check bounds and does not add elements. What you are doing is writing to and reading from the buffer which vector uses, but that is considered undefined behavior.


You should use one of these methods to add to vectors.

.push_back(0) the default method - appends to the end

.resize(num,0) resizes the vector up (or down) to num and sets the value of the new elements to the 2nd arg, 0.

The vector can also be constructed with an initial size - vector(num,0) is more or less identical to v = vector();v.resize(num,0)


On the other end, to do this safely, you can use .at(n) to access elements, and this will throw an std::out_of_range exception if you access beyond the bounds.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
2

Is this in the realm of undefined behavior?

Yes.

Remember that the general rule of C++ arrays and std::vector is that you cannot access elements you aren't entitled to. A fresh std::vector has a size of 0, meaning that it logically contains no elements (is empty), and therefore it is undefined for you accessing such non-existent elements (speaking about reaching into the void ;))

The operator[] of std::vector only accesses elements inside the vector, no more, no less. Doing my_vector[0] on an empty vector does exactly what is said in the former paragraph. You are accessing something you are not entitled to access. Please note that this is not just when you are modifying the non-existing element. Even just reading it is undefined.

What is going on here? Is this simply writing the 1 into reserved memory space, and I should expect this to blow up in my face, right?

You're just absolutely lucky it didn't literally blew up in your face[1]. :)


[1] There are sources that the chances of this happening is actually higher than what you think. Thus, you should beware, and practice safe(r) coding.

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94