Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Constructor/Pointer problem (http://www.go4expert.com/forums/constructor-pointer-problem-t1088/)

Happypuppet 29Jul2006 01:04

Constructor/Pointer problem
 
Code:

class cClass
{
private:
struct sNode
{
        sNode* Next;
};
sNode* First;

public:
cClass()
{
        First = NULL;
}
~cClass()
{
        sNode* tmp;
        while( First != NULL )
        {
                tmp = First;
                First = tmp->Next; // ***
                delete tmp;
        }
}
};

class cBiggerClass
{
private:
cClass* myclass;

public:
cBiggerClass()
{
        myclass = new cClass;
}
~cBiggerClass()
{
        delete myclass;
}

This is a portion of two classes in one of my programs (code has changed identifiers), which implements a linked list as a part of it. It's part of a framework which I just finished the most basic parts of, so I'm doing the first building, running, and debugging before I start incrementally adding things.

In this small test run, cBiggerClass is instantiated once and almost immediately destroyed afterwards. When that happens, cClass also gets destroyed, without any nodes having been created in the list. The problem is right then I get an exception at the *** line for an invalid address pointer on First. Apparently in cClass's destructor, the loop is actually being entered and it tries to figure out where First->Next goes, when of course First hasn't been initialized.

Through some experimentation with break points, it seems like cClass's constructor does not get called. Thus First seems to point to a random place, causing it to enter the loop. The debugger says First->Next is undefined when the error occurs.

Anyone have any idea why?

Happypuppet 29Jul2006 05:13

Re: Constructor/Pointer problem
 
(I apologize if a double post is prohibited, but where's the edit button?)

Fixed the problem. VS2003 decided that the Build option would display things yet do nothing, and thus was still running a bugged program in which First had not been initialized. Had to use the Clean option first to get it using the right code. How incredibly stupid of it... ah well. Is there an option or something that makes it do this?

shabbir 29Jul2006 17:46

Re: Constructor/Pointer problem
 
Rebuild ALL option will clean and then build it.


All times are GMT +5.5. The time now is 23:19.