Zhou Lei wrote:
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?
You don't check for NULL lchild/rchild in ntree(). That could be a
problem. Add the checks, something like this:
p->lchild = (lchild ? lchild->ntree() : 0);
p->rchild = (rchild ? rchild->ntree() : 0);
Also, what if 'p = new ptree;' fails? You're not catching the
exception. Since about 1994 the C++ Std has said that 'new'
throws a 'std:bad_alloc' exception on error; 'new' does not return
NULL on error UNLESS the 'nothrow' syntax is used:
#include <new>
.
.
.
p = new (nothrow) ptree;
Ref:
http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=37
Regards,
Larry