Click to See Complete Forum and Search --> : Found my problem


jshyus
August 1st, 2002, 08:29 AM
I finally found the problem in my code.
I posted earlier that when I debug into my program it keeps crashing on a "new" operator but it runs fine. Now I found the cause of the problem. It is because I tried to access an object that was already deleted. It took me couple of days to find this problem. I don't know how you guys do it but I used _CrtCheckMemory to check the heap in all suspected areas. Right after I tried to access the deleted object, the program crashed in _CrtCheckMemory().

I still do not know why it runs fine and crashes when I debug it. Is the heap somehow different in the two cases?

Graham
August 1st, 2002, 09:14 AM
That's one of the reasons why we keep going on about avoiding the use of naked pointers in your code. Wrap new and delete in the RAII idiom (resource acquisition is initialisation) - acquire a resource inthe class constructor and release it in the destructor. Use the STL containers, rather than newing memory for an array. Etcetera.

jshyus
August 1st, 2002, 12:40 PM
Is this a C++ exception? I was not able to catch anything.

Here is the problem in my code:

class SomeObj
{
int x;
}

class A
{
SomeObj *obj;
}

main
{
A a;
SomeObj *newobj = new SomeObj;
a.obj = newobj;

// somewhere
delete newobj;

// Error! try to acess delete object
(a.obj)->x = 1;
}

Graham
August 2nd, 2002, 04:57 AM
It's not an exception: it's undefined behaviour. IOW you can't predict what will happen if you do it (most likely is that your program will crash spectacularly or that you will trample over memory, and THEN your program will crash spectacularly).

stober
August 2nd, 2002, 06:00 AM
Thats also the reason to initialize all class objects to some known value, normally 0 or NULL in the class constructor and to reinitialize it after deleting a pointer. Makes it a lot easier to see the problem when you see the address of a pointer is 0.

willchop
August 18th, 2002, 11:23 AM
This is how I would go about it:

class SomeObj
{
public:
SomeObj() : m_x(0) {}
SomeObj(const int x) : m_x(m) {}

protected:
int m_x;
}

class A
{
public:
A() : m_obj(new SomeObj) {}

protected:
std::auto_ptr<SomeObj> m_obj;
}

main
{
A a;
}

Regards, willchop

Graham
August 18th, 2002, 02:47 PM
If you're going to use auto_ptr in your class, then you are going to have to write your own copy ctor and copy assignment operator (or, more likely, disable them both). The compiler generated function will almost certainly do exactly the wrong thing.

willchop
August 19th, 2002, 12:37 PM
A "deep copy" is also needed for classes with raw pointer member
variables. One solution would be to use the boost::shared_ptr.

Regards, willchop