MFC代码中CWnd :: SetWindowText的内存泄漏 [英] Memory leak in MFC code at CWnd::SetWindowText

查看:123
本文介绍了MFC代码中CWnd :: SetWindowText的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在我的一个对话框的OnBnClickedOK()方法中的MFC SDI应用程序中检查内存泄漏.
我已经找到了由于以下代码中的GetWindowText行导致的内存泄漏.

Hi,
I am checking for memory leaks in my MFC SDI app, in the OnBnClickedOK() method for one of my dialogs.
I have tracked down a memory leak to be due to the GetWindowText line in my code below.

void CMyDlg::OnBnClickedOk()
{
		CWnd* pWnd = GetDlgItem(IDC_EDIT1);

		CString sequenceName;

		pWnd->GetWindowText(sequenceName);



谁能告诉我为什么会发生泄漏.我正在使用CMemoryState检查内存泄漏,如下所示,并且diffMemState.m_lCounts [1]的值为1.



Can anyone please tell my why the leak occurs. I am using CMemoryState to check for memory leaks, as shown below, and diffMemState.m_lCounts[1] has a value of 1.

#ifdef _DEBUG
   newMemState.Checkpoint();
   if( diffMemState.Difference( oldMemState, newMemState ) )
   {
	TRACE("Memory leaked!\n" );
      	AfxMessageBox(L"Memory leaked!\n" );
   }
#endif
		pWnd->GetWindowText(sequenceName);
#ifdef _DEBUG
   newMemState.Checkpoint();
   if( diffMemState.Difference( oldMemState, newMemState ) )
   {
	TRACE("Memory leaked!\n" );
	AfxMessageBox(L"Memory leaked!\n" );
   }
#endif

推荐答案

pWnd->GetWindowText(sequenceName);


在CString中分配在字符串超出范围之前不会释放的内存..

CString(随版本而异)使用指针共享和延迟的垃圾回收.

因此,即使超出范围,内存也可能会挂起一段时间.

在程序关闭之前,内存泄漏检测不一定有效.

******


将以下宏放在标头包含的每个CPP文件中.


Allocates memory in the CString which won''t be freed until the string goes out of scope..

CString (varies with version) uses pointer sharing and delayed garbage collection.

So it''s possible that the memory may hang around a while even after it goes out of scope.

Memory Leak detection won''t necessarily be valid until your program is closing.

******


Put the following macros in every CPP file after your header includes.

#ifdef _DEBUG
#define new DEBUG_NEW
#endif



这将使调试器可以跟踪每个内存分配,如果有泄漏,则会在程序退出时向您显示这些位置(在输出窗口中).



This will allow the debugger to track every memory allocation and if you have leaks will show you those locations (in the output window) when the program exits.


这篇关于MFC代码中CWnd :: SetWindowText的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆