Dynamic memory problem

Hey,

At the beginning of my code, I have this line:

Shape* gShape = 0;

As this is dynamic memory, I delete it at the end:
delete gShape;
gShape = 0;

This compiles fine and runs fine, but as soon as I close the program, I get a "not working anymore" window from the OS (you know which I mean; "send this to microsoft bleeeeh"). It only crashes this way when I actually use the Shape instance, so when I use gShape = new class(parameters);. If I don't use the instance (I keep it 0), it doesn't crash.

What am I doing wrong?

Thank you!
You can't delete something you don't create. You need to assign the pointer to an object created in the heap with new.
Well, that's actually the problem. When I don't assign the pointer to an object it works fine, when I assign one with "new", it crashes.
Then you're doing it wrong. Post your code.
Sure :)

So I first have this line:
Shape* gShape = 0;

In the program, the pointer is assigned to it. This points to an object which is childclass of Shape, so it's something like:
gShape = new Line(parameters);

My destructor is virtual in the Shape class; no more destructors in the childclasses. It looks like:

Shape::~Shape()
{
DeleteObject(pen);
DeleteObject(brush);
}

pen and brush are data members of Shape. If I remove this destructor and try to delete the object, I get a _BLOCK_TYPE_IS_VALID-error. What am I doing wrong/what's happening here?

Thank you



Last edited on
It's not enough code to tell, but I'm guessing pen and brush are invalid pointers.
If you have not implemented a copy constructor and assignment operator for Shape, then I suggest
declaring them private and try to compile.

In almost all cases where a class dynamically allocates memory that it frees in the destructor you
either have to make the object non-copyable or define your own copy constructor and assignment
operator.

If after making the change I suggested your code does not compile, then you are attempting either
to copy an object or assign an instance to another, both of which will result in two instances
attempting to DeleteObject() the same pen and brush.
Topic archived. No new replies allowed.