intmain(){ std::vector<int> v{42}; cout<<v.at(5)<<endl; //Will crash, and coredump return0; }
编译运行时可能出现如下现象:
1 2 3 4 5
$ g++ -o t_vec ./test_vec.cpp $ ./t_vec terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 5) >= this->size() (which is 1) Aborted (core dumped)
使用 gdb 打开来看:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
$ gdb t_vec core Core was generated by `./t_vec'. Program terminated with signal SIGABRT, Aborted. #0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51 51 ../sysdeps/unix/sysv/linux/raise.c: No such file or directory. (gdb) i s #0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51 #1 0x00007fbe77c7f801 in __GI_abort () at abort.c:79 #2 0x00007fbe782d4957 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #3 0x00007fbe782daab6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #4 0x00007fbe782daaf1 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #5 0x00007fbe782dad24 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #6 0x00007fbe782d6855 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6 #7 0x000055a4f8cda08a in std::vector<int, std::allocator<int> >::_M_range_check(unsigned long) const () #8 0x000055a4f8cd9e9d in std::vector<int, std::allocator<int> >::at(unsigned long) () #9 0x000055a4f8cd9c11 in main () (gdb)