Search code examples
c++memory-leakswcharwidechar

GetText() memoryleak


This is my first post so be gentle :D

I just started at this job and my first task was to find the leak which I did, pointed out by the comment. I control clicked gettext() and I get

virtual System::WideChar * __fastcall GetText(void); 

I added 5 extra pwide and the leak increased (memory usage in task master increased by 1000).

I tried delete and free but i get exceptions. Anyone got any advice on how to plug the leak?

Here is my code:

UnicodeString CReportManager::GetFinalHTML()
{
UnicodeString ret = "";
ret = "<Reports>";

if( ErrorHTML->Count )
{
    ret += "<Errors>" + UnicodeString(ErrorHTML->GetText()) + "</Errors>";
}

//System::WideChar *pWide= ReportHTML->GetText();
//System::WideChar *pWide4= ReportHTML->GetText();
//System::WideChar *pWide1= ReportHTML->GetText();
//System::WideChar *pWide2= ReportHTML->GetText();
//System::WideChar *pWide3= ReportHTML->GetText();
    //delete pWide;
   //   free(pWide);
    //ret +=pWide;
ret += ReportHTML->GetText();          //leak here
ret += "</Reports>";

#ifdef _DEBUG
ReportHTML->SaveToFile("C:\\debug.xml");
#endif

delete ReportHTML;
delete ErrorHTML;

ReportHTML = NULL;
ErrorHTML = NULL;


return ret;
}

Solution

  • Ok I found the answer, if anyone has the same problem, the solution is StrDispose(pWide); I tried it with all 4 extra pWide and my memory leak was gone :

    UnicodeString CReportManager::GetFinalHTML()
    {
        UnicodeString ret = "";
        ret = "<Reports>";
    
        if( ErrorHTML->Count )
        {
            ret += "<Errors>" + UnicodeString(ErrorHTML->GetText()) + "</Errors>";
        }
    
        System::WideChar *pWide= ReportHTML->GetText();
    
        //delete pWide;
        //free(pWide);
        ret +=pWide;
        StrDispose(pWide);
    
        //ret += ReportHTML->GetText();          //leak here
        ret += "</Reports>";
    
    #ifdef _DEBUG
        ReportHTML->SaveToFile("C:\\debug.xml");
    #endif
    
        delete ReportHTML;
        delete ErrorHTML;
    
        ReportHTML = NULL;
        ErrorHTML = NULL;
    
        return ret;
    }