Destructor being called twice ?

V

vivekian

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 .
 
A

Alf P. Steinbach

* vivekian:
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 ?

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.
 
P

Puppet_Sock

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top