以下是我程序的代码:
CString strWorkerThreadMsg;strWorkerThreadMsg.Format("%s-%s-%s  %s:%s:%s  %s", \
_T2STR(curTime.GetYear()), _T2STR(curTime.GetMonth()), _T2STR(curTime.GetDay()), \
_T2STR(curTime.GetHour()), _T2STR(curTime.GetMinute()), _T2STR(curTime.GetSecond()), \
strMsg);

CString *s = new CString(strWorkerThreadMsg);
::PostMessage(m_curGUIHWND, UWM_WT_REPORT, 0 ,(LPARAM)s);
delete s;
return;
当我不写delete s语句的时候,程序没有问题。但是此时会有内存泄漏。当我写此语句的时候,程序出错,调试时候,跟踪代码到如下代码行停止:
CString::CString(const CString& stringSrc)
{
ASSERT(stringSrc.GetData()->nRefs != 0);
if (stringSrc.GetData()->nRefs >= 0)
{
ASSERT(stringSrc.GetData() != _afxDataNil);
m_pchData = stringSrc.m_pchData;
InterlockedIncrement(&GetData()->nRefs);
}
else
{
Init();
*this = stringSrc.m_pchData;
}
}
停止于ASSERT(stringSrc.GetData()->nRefs != 0);

解决方案 »

  1.   

    在UWM_WT_REPORT的消息处理中释放
      

  2.   

    CString *s = &strWorkerThreadMsg;
      

  3.   

    CString *s = new CString(strWorkerThreadMsg);
    ::PostMessage(m_curGUIHWND, UWM_WT_REPORT, 0 ,(LPARAM)s);
    delete s;
    ==
    你这样肯定不行啊。我知道你用new的目的应该是想在响应事件中能够用到s这个对象。但是,postMessage函数是非阻塞的,发送完消息后并不等待返回,所以立马就执行了delete s了。也就是说,s已经被释放了。此时,消息响应函数中会对s进行操作,自然就完蛋了。因此,你用了new,但是没有达到效果,和s是普通的局部变量没有区别。
    修改的办法,一是将PostMessage改为SendMessage;二是s的释放由响应UWM_WT_REPORT消息的响应函数来删除,即delete s有该响应函数执行,而不是你这个函数中