help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Anyone could help me with this memeory problem...


From: Zhou Lei
Subject: Re: Anyone could help me with this memeory problem...
Date: Wed, 23 Feb 2005 09:46:40 +0000
User-agent: Mozilla Thunderbird 1.0 (X11/20041206)

Larry I Smith wrote:
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

Thanks for your reply, and yes it is not a good style without checking the excptions. In this program, the ntree() will return 0 to the calling statement if this==0, so "p->lchild=lchild->ntree()" has the same meaning with "p->lchild=(lchild ? lchild->nree() : 0) that you wrote. And I am confused why "new" failed to allocate memory on my machine (without any exceptions thrown, just crash and say "segmentation fault").


reply via email to

[Prev in Thread] Current Thread [Next in Thread]