Vector going out of bounds without giving error

99封情书 提交于 2019-11-26 02:58:46

问题


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
}

回答1:


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.




回答2:


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++

  • Debug mode -- general info about libstdc++ debugging
  • _GLIBCXX_DEBUG
  • _GLIBCXX_CONCEPT_CHECKS, with -fconcepts -- enable c++ concepts

clang libcxx

  • _LIBCPP_DEBUG_LEVEL=1

boost

  • BOOST_DISABLE_ASSERTS -- disable asserts in the boost library.

Microsoft

  • Checked Iterators
  • _ITERATOR_DEBUG_LEVEL -- set iterator debug level
  • Security Features in the CRT
  • _CRT_SECURE_NO_WARNINGS : disable deprecation warnings
  • _SCL_SECURE_NO_WARNINGS -- less safe(according to microsoft), but more standard compliant:

  • _SECURE_SCL -- old method of setting iterator debug level

  • _HAS_ITERATOR_DEBUGGING - deprecated macro

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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/16620222/vector-going-out-of-bounds-without-giving-error

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