Connecting Tech Pros Worldwide Forums | Help | Site Map

Destructor being called twice ?

vivekian
Guest
 
Posts: n/a
#1: Mar 24 '06
Hi ,

Have the following piece of code ,

class ClientList {
public:
char * hostName ;
int portNo ;
struct timeval * tv ;
ClientList ()
{
this -> hostName = new char [40] ;
....
}
~ClientList ()
{
delete [] (this -> hostName) ;
}
};

While running , everything works fine and the destructor is called. But
it seems like the compiler tries to free this memory again on its own ,
giving the following error on g++
*** glibc detected *** double free or corruption (fasttop): 0x0804d008
***

is there something wrong which is being done here ?
thanks in advance .

Alf P. Steinbach
Guest
 
Posts: n/a
#2: Mar 24 '06

re: Destructor being called twice ?


* vivekian:[color=blue]
> Hi ,
>
> Have the following piece of code ,
>
> class ClientList {
> public:
> char * hostName ;
> int portNo ;
> struct timeval * tv ;
> ClientList ()
> {
> this -> hostName = new char [40] ;
> ....
> }
> ~ClientList ()
> {
> delete [] (this -> hostName) ;
> }
> };
>
> While running , everything works fine and the destructor is called. But
> it seems like the compiler tries to free this memory again on its own ,
> giving the following error on g++
> *** glibc detected *** double free or corruption (fasttop): 0x0804d008
> ***
>
> is there something wrong which is being done here ?[/color]

Yes.

The main problem is that you're using low-level pointers when you should
be using e.g. std::string.

As a consequence, things happen that you didn't think of, here automatic
copy construction and assignment. You can fix those two concrete bugs
by defining a copy constructor and assignment operator. But you cannot
fix the general problem of things occuring that you didn't think of,
except by using safer standard library classes like std::string, where
the authors /did/ think of most untoward things that can occur.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Puppet_Sock
Guest
 
Posts: n/a
#3: Mar 24 '06

re: Destructor being called twice ?


vivekian wrote:
[example of class with pointer to resource snipped][color=blue]
> is there something wrong which is being done here ?[/color]

Yes. Look up "the rule of three." If a class has a resource
that is pointed at by a member variable, it almost certainly
wants to have dtor, copy ctor, and assignment operator.
The default copy ctor does a shallow copy. So, for example,
if you call a function that takes an instance of your class,
it makes a copy. And the copy will point at the same chunk
of memory. When the copy is deleted it will delete that
same chunk of memory, producing exactly your problem.
Socks

Closed Thread