X
xman
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.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.left = x;
b.right = y;
there is no segmentation fault anymore. It seems to me the original
code has the b value cached, hence, during the assignment to
b.right, it uses old b 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.left = build_recursive(n-1);
b.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 ;
}
compiler. However, when I use gcc 4.2.0, the assignment to b.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.left = x;
b.right = y;
there is no segmentation fault anymore. It seems to me the original
code has the b value cached, hence, during the assignment to
b.right, it uses old b 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.left = build_recursive(n-1);
b.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 ;
}