Click here to Skip to main content
16,020,103 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi, guys:

What's wrong with this picture -- -- "Expression: _CrtIsValidHeapPointer(pUserData)".

The exception was caught when I was debugging in a class, codes like below:

class Myclass
{
   Myclass(){
   m_data = new char[50];
   m_data = "You are someone!!";
   }
   ~Myclass(){delete []m_data;}
   
   void SetStr(char *para)
   {
        (NULL == para)
            return;
        if(m_data != para)
        {
            delete []m_data; // The exception was caught here, debugging stopped.
            m_data = NULL;
            m_data = new char[strlen(para)+1];
            strcpy(m_data,para);
        }

   }
private:
   char *m_data;
}



int main(int argc, char* argv[])
{
   Myclass *pMyclass = new Myclass();
   pMyclass->SetStr("Weak !!! ");
   delete  pMyclass;
}




My project was more complicated than what I presented here, but the context about 'm_data' usage was almost the same.

What's the problem while I was trying to release m_data's memory,"delete []m_data", how can I do to avoid?
Posted

The way you work with m_data is a nonsense.
Looking the MyClass::MyClass constructor, you first allocate 50 chars from the heap, assigning the address to m_data, then you assign to m_data the address of the literal "You are someone". Since this point, the 50 chars you allocate are leaked (and unreachable) with m_data pointing to a constant literal, that you try do delete later on, in the destructor and in SetStr.

In MyClass::SetStr there is a (NULL==para) return;. It will make more sense if you place an if in front (is it a typo?!?).

In practice, string literal and character arrays don't work the way you think.
In particular
m_data = "You are someone!!";

doesn't copy the string into the array pointed by m_data.

To properly copy you should use library fuctions like strcpy or similar, the does a work like this:

C++
void copy_string(char* dest, unsigned dest_sz, char* src)
{
    unsigned i;
    for(i=0; i<dest_sz-1 && src[i]; ++i)
        dest[i] = src[i];
    dest[i]='\0';
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-Mar-11 21:41pm    
Best answer; and "nonsense" is a very accurate characteristic, so a 5.
--SA
scu_sundy 25-Mar-11 6:37am    
Thank you, Emilio.my 5.
The first time you go in, the pointer is not to heap memory: it is to static memory!
MIDL
m_data = "You are someone!!";
 
Share this answer
 
Comments
scu_sundy 20-Mar-11 6:45am    
Thanks Griff, you saved me again! my 5
OriginalGriff 20-Mar-11 6:51am    
You're welcome!
Sergey Alexandrovich Kryukov 20-Mar-11 21:40pm    
Let them reclaim static memory, very useful exercise :-). My 5.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900