Constructor/Pointer problem

Discussion in 'C' started by Happypuppet, Jul 28, 2006.

  1. Happypuppet

    Happypuppet New Member

    Joined:
    Jul 28, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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?
     
  2. Happypuppet

    Happypuppet New Member

    Joined:
    Jul 28, 2006
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    (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?
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,376
    Likes Received:
    388
    Trophy Points:
    83
    Rebuild ALL option will clean and then build it.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice