確認環境
$ g++ --version
g++ (Homebrew GCC 9.2.0) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
調査
_GLIBCXX_DEBUG あり
test.cpp
#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> a(5);
cout << "---1---" << endl;
a[1] = 20;
cout << a[1] << endl;
cout << "---2---" << endl;
a[10000000] = 99;
}
出力結果
---1---
20
---2---
/usr/local/Cellar/gcc/9.2.0/include/c++/9.2.0/debug/vector:427:
In function:
std::__debug::vector<_Tp, _Allocator>::reference
std::__debug::vector<_Tp,
_Allocator>::operator[](std::__debug::vector<_Tp,
_Allocator>::size_type) [with _Tp = int; _Allocator =
std::allocator<int>; std::__debug::vector<_Tp, _Allocator>::reference =
int&; std::__debug::vector<_Tp, _Allocator>::size_type = long unsigned
int]
Error: attempt to subscript container with out-of-bounds index 10000000, but
container only holds 5 elements.
Objects involved in the operation:
sequence "this" @ 0x0x7ffeebcfa610 {
type = std::__debug::vector<int, std::allocator<int> >;
}
Abort trap: 6
_GLIBCXX_DEBUG なし
test.cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> a(5);
cout << "---1---" << endl;
a[1] = 20;
cout << a[1] << endl;
cout << "---2---" << endl;
a[10000000] = 99;
}
出力結果
---1---
20
---2---
Segmentation fault: 11
_GLIBCXX_DEBUG ありだと、エラーの原因も記載されています。