473,287 Members | 1,659 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

Access violation error: object is deleted twice

Hi,

The code below produces an access violation error, complaining that an object
is destroyed twice.

I don't understand why this happens. Any help would be appreciated.

--------main.cpp---------------------------------------------------------------------------
#include "AbstractActivator.h"
// 3 classes involved:
// TextDisplayer: Base class for a hierarchy of functors that
// display a string in a certain way.
//
// Activator: Base class for a hierarchy.
//
// ActivatorFactory: Base class of a hierarchy of functors
// taht return a pointer to a std::list<Activator>
//
int main()
{

// If I don't create any intances of
// TextDisplayer, I don't get any errors
TextDisplayer show;
// ActivatorFactory is a functor that returns
// a pointer to an stl::list<Activator>
// Each Activator instance contains a pointer
// to a TextDisplayer instance. This internal instance
// is deleted in the Activator destructor.
ActivatorFactory fact;

// Activartors is a typedef for stl::list<Activator>
Activators * acts = fact();
Activators::iterator i;

// Call the activate method of all activators
for(i = acts->begin(); i != acts->end(); ++i)
{
(*i).activate();
}

// Delete the dynamically created list<Activators>
// This is were I get into trouble. This calls
// the destructor of Activator, that tries to delete
// the internal TextDisplayer. That line creates an
// error, complaining that that memory area has already
// been deleted.
delete acts;

return 1;
}

----------------end main.cpp---------------------------------------

----------abstractactivators.cpp-----------------------------------

#include <string>
#include <list>
#include "AbstractActivator.h"

// TextDisplayers
void DialogDisplayer::operator()(const std::string & aMessage)
{
//::ShowMessage(AnsiString(aMessage.c_str()));
}

// Activators
bool Activator::activate()
{
//Método base solo usado para debug
//Los específicos deben de tener en cuenta los
// posibles errores.
return true;
}

Activator::Activator(TextDisplayer * aDisplayer)
:theDisplayer(aDisplayer)
{
//do nothing
}

Activator::~Activator()
{
delete theDisplayer;
}
// Factory
Activators * ActivatorFactory::operator()(const ActivatorType aType)
{

Activators * lst = new Activators;
Activator act(new TextDisplayer);
lst->push_back(act);

return lst;
}

---------end activators.cpp-----------------------------------------------

--------activators.h-----------------------------------------
#ifndef ABSTRACT_ACTIVATOR_FLAG
#define ABSTRACT_ACTIVATOR_FLAG

#include <string>
#include <list>

class TextDisplayer
{
public:
TextDisplayer(){};
virtual ~TextDisplayer() {};
virtual void operator() (const std::string & aMessage) {};

};

class DialogDisplayer
:
TextDisplayer
{
public:
DialogDisplayer():TextDisplayer(){};
virtual ~DialogDisplayer() {};
virtual void operator() (const std::string & aMessage);
};

class Activator
{
public:
Activator(TextDisplayer * aDisplayer);
virtual ~Activator();
virtual bool activate();

private:
TextDisplayer* theDisplayer;
};
enum ActivatorType
{
NullActivator
};

typedef std::list<Activator> Activators;

class ActivatorFactory
{
public:
virtual Activators * operator()(const ActivatorType aType = NullActivator);
};

#endif //ABSTRACT_ACTIVATOR_FLAG

----------end-------------------------------------------

Jul 19 '05 #1
5 3607
Boogie El Aceitoso wrote:
Hi,

The code below produces an access violation error, complaining that an object
is destroyed twice.

I don't understand why this happens. Any help would be appreciated.


Classic duh problem.

It's due to this:

// Factory
Activators * ActivatorFactory::operator()(const ActivatorType aType)
{

Activators * lst = new Activators;
Activator act(new TextDisplayer);
lst->push_back(act);

return lst;
}

On destruction of Activator you delete a TextDisplayer. However
lst->push_back(act) makes a copy of act. act is later destroyed (on
exit from the method) and you inadvertently just deleted the
TextDisplayer object you just created. A potential solution is to use
reference counting. Or another (example below) is simply to add the
pointer to the list once it's in the list. Yet another is that there are
other list implementations that do not use the copy constructor at all.
Try this:

// Factory
Activators * ActivatorFactory::operator()(const ActivatorType aType)
{

Activators * lst = new Activators;

lst->push_back(Activator());

Activators::iterator iter = lst->end();
-- iter;
(*iter).SetDisplayer( new TextDisplayer );

return lst;
}

add this method to class Activator

virtual void SetDisplayer( TextDisplayer* d )
{
TextDisplayer* old = theDisplayer;
theDisplayer = d;
delete old;
}

Jul 19 '05 #2
On 01 Oct 2003 16:10:51 GMT, Gianni Mariani <gi*******@mariani.ws> wrote:

On destruction of Activator you delete a TextDisplayer. However
lst->push_back(act) makes a copy of act. act is later destroyed (on
exit from the method) and you inadvertently just deleted the
TextDisplayer object you just created.


Aaarrrrgghhh!
Do all STL containers do this? If I add a pointer to a dynamically created
Activator (instead of one in the stack), will it follow the pointer and make a
copy of the object?

Maybe I should just add a copy constructor to Activator and TextDisplayer...

Thanks! :-)

Jul 19 '05 #3

"Boogie El Aceitoso" <fr****@telefonica.net> wrote in message news:2n********************************@4ax.com...
Do all STL containers do this? If I add a pointer to a dynamically created
Activator (instead of one in the stack), will it follow the pointer and make a
copy of the object?
Everythying in C++ does this (not just the standard containers). If yoiu want
to deep copy an object, you need to provide that in the copying operations.

Maybe I should just add a copy constructor to Activator and TextDisplayer...

This is precisely what you must do. Add a copy assignment operator as well.
Either that or put the data in a class such as vector or string that had the proper
copying semantics already.
Jul 19 '05 #4
Ron Natalie wrote:
"Boogie El Aceitoso" <fr****@telefonica.net> wrote in message news:2n********************************@4ax.com... ....
This is precisely what you must do. Add a copy assignment operator as well.
Either that or put the data in a class such as vector or string that had the proper
copying semantics already.


The vector comment is ambiguous, not sure what you mean.

If you can't make copies of TextDisplayer then copying the Activator
would only be portable if you reference counted (or garbage collected in
some way) the TextDisplayer objects being pointed to.

Jul 19 '05 #5
On Wed, 01 Oct 2003 17:18:11 +0000, Gianni Mariani wrote:
Ron Natalie wrote:
"Boogie El Aceitoso" <fr****@telefonica.net> wrote in message news:2n********************************@4ax.com... ...

This is precisely what you must do. Add a copy assignment operator as well.
Either that or put the data in a class such as vector or string that had the proper
copying semantics already.


The vector comment is ambiguous, not sure what you mean.


What he means is that instead of storing a pointer to an object, store an
actual object. Do you really need to store a pointer to a TextDisplayer?

Two uses of pointers are for C-style arrays and strings,
which can be almost drop-in replaced with std::vector and std::string,
respectively. For most other pointer uses, you can use a handle class with
deep-copying semantics.
If you can't make copies of TextDisplayer then copying the Activator
would only be portable if you reference counted (or garbage collected in
some way) the TextDisplayer objects being pointed to.


Or deep-copy the TextDisplayer.

Josh
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Allen | last post by:
Hi all, I tried posting to one of the ms.win32 groups and haven't gotten a response yet. It may be my C++ that's at fault anyway so I'll try here too. I wrote a .dll that is misbehaving...
6
by: J Smith | last post by:
After doing some googling through the lists and such, I wasn't able to arrive at a solution for a problem I've run into recently. I've seen mention of similar symptoms, but my case seems different....
8
by: doomx | last post by:
I'm using SQL scripts to create and alter tables in my DB I want to know if it's possible to fill the description(like in the Create table UI) using these scripts. EX: CREATE TABLE(...
0
by: techie | last post by:
I have created an event sink in my ATL COM project. The event sink receives events from a C# component. There is no problem with receiving events but when my COM object is released I get an...
2
by: Vladimir O¾ura | last post by:
I am building a pocket pc application that requires a datagrid. I am inserting a new row this way: private void mInsert_Click(object sender, System.EventArgs e) { try { DataRow dr =...
0
by: techie | last post by:
Hi, I've created a COM object in VC++ that I call from XMetal. I pass the COM object (via a XMetal macro) my XMetal Application object by a put_ method. In my put_ method I call QueryInterface...
0
by: Steven Nagy | last post by:
Hidey ho, This question relates to IDbDataAdapter, DataSets, XML, and DiffGrams. I have a data adapter of type IDbDataAdapter and a dataset with one table in it, which has one row in it, which...
2
by: jthep | last post by:
I'm trying to get this piece of code I converted from C to work in C++ but I'm getting an access violation error. Problem occurs at line 61. Someone can help me with this? The function...
39
by: Martin | last post by:
I have an intranet-only site running in Windows XPPro, IIS 5.1, PHP 5.2.5. I have not used or changed this site for several months - the last time I worked with it, all was well. When I tried it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.