#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string name;
std::vector<double> v(5, 1);
std::cout<<v.capacity()<<std::endl;
v[1000000]= 10.;
std::cout<<v[1000000]<<std::endl;
std::cout<<v.capacity()<<std::endl;
return 0;
}
Is this code undefined behavior ? It seems that no allocation is made on the fly so I am wondering how the program is able to handle the item assignment. I am using OSX Monterrey and this prints "10" as "expected".
std::vector<double> v(5, 1);
std::cout<<v.capacity()<<std::endl;
v[1000000]= 10.;
From your question, I'm pretty sure you know this is undefined behavior. Your question is really "why doesn't this crash?"
Undefined behavior means anything can happen. Usually what happens is the app seems to work. The vector will ask std::allocate
for ~20 bytes of memory, and std::allocate
will ask the operating system for a large chunk of memory, and then std::allocate
will give 20 bytes of memory to the vector, and then it will save the rest of the large chunk for whatever next asks for more memory. Then your code assigns 10
to the place in (virtual) memory that's ~4MB past the memory allocated to the vector.
One possibility from there, is that that address in memory is not currently allocated in your process. The OS will detect this and usually it will crash your app. Or it might just give that memory to your app so that it keeps running. So you never really know what will happen.
Another option is that If that address in memory happens to already be allocated in your process, either coincidentally by std::allocate
, or coincidentally by something else, then the write succeeds in writing 10
to that place in memory. Hopefully that wasn't important, like networking code, in which case the next network call could send the contents of your memory, including your passwords, to whatever server it happened to be talking to at the time. Or maybe that memory isn't currently used for anything at the moment, and nothing breaks. Or maybe it works a 998 times in a row, and then on the 999th time it erases your files. Unlikely, but possible.
So yes, most of the time "undefined behavior works anyway". But don't do it, you will regret it.