I'm a newbie to use C++, and I wrote a little program it can create a
binary tree. But when the copy constructor or the assignment (overloaded
one) occurs, the program doesn't run as I expect. The copy construtor is
like this:
ptree::ptree(const ptree& pt){
weight=pt.weight;
c=pt.c;
lchild=pt.lchild->ntree(); // Copy left sub tree recursively using
// ntree()
rchild=pt.rchild->ntree(); // Copy right sub tree.
}
That function invokes this function to complete the copy tree jobs
recursively.
ptree* ptree::ntree() const{
ptree* p;
if (!this)
return 0;
p = new ptree;
p->c = c;
p->weight = weight;
p->lchild = lchild->ntree(); // Copy the left sub tree recursively.
p->rchild = rchild->ntree(); // Copy right sub tree.
return p;
}
On my computer the tree was not built correctly, and I traced into the
functions and I found that the "segment fault" occurs when I step into
"new" keyword (functions of system library may be invoked). My machine
is running Debian Linux (kernel 2.4.18) and the program is compiled with
g++ (version 3.4). But everything's okay on a UNIX machine (Solaris on
SPARC). I'm not sure whether it's a bug or not, and the source code is
attached, could anyone give me some suggestions?