Vector going out of bounds without giving error

断了今生、忘了曾经 提交于 2019-11-26 12:30:00
kgraney

STL vectors perform bounds checking when the .at() member function is called, but do not perform any checks on the [] operator.

When out of bounds, the [] operator produces undefined results.

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.

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.

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. Please post code.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!