The codes below basically builds a binary tree. It runs well on Intel compiler. However, when I use gcc 4.2.0, the assignment to b[i].right causes segmentation fault. Tracing with valgrind reveals that the particular memory address was deleted during push_back().
If I change the assignments to int x = build_recursive(n-1); int y = build_recursive(n-1); b[i].left = x; b[i].right = y; there is no segmentation fault anymore. It seems to me the original code has the b[i] value cached, hence, during the assignment to b[i].right, it uses old b[i] which may be invalidated after push_back() due to resize. Any ideas? Compiler problems? or non-trivial bugs? Thanks. #include <vector> using std::vector; class A { public: int left; int right; }; class B { public: void build(int n) { b.clear(); next_index = 0; int root = build_recursive(n); } int build_recursive(int n) { int i = get_next_index(); if (n > 0) { b[i].left = build_recursive(n-1); b[i].right = build_recursive(n-1); } return i; } int get_next_index(void) { A a; b.push_back(a); int index = next_index++; return index; } int next_index; vector<A> b; }; int main(int argc, char* argv[]) { B tree; tree.build(14); return 0 ; } -- Summary: vector push_back()/resize() causes assignment to deleted memory Product: gcc Version: 4.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ AssignedTo: unassigned at gcc dot gnu dot org ReportedBy: cshinyee at gmail dot com GCC host triplet: Linux GCC target triplet: x86_64 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=32068