gpt4 book ai didi

c++ - 试图了解内存泄漏

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:34 25 4
gpt4 key购买 nike

我正在使用 VLD(视觉泄漏检测器),它检测到一些内存泄漏。我试图理解为什么这是 VLD 的内存泄漏。这可能是误报?

代码很简单:

    CGlobalLog* CGlobalLog::m_instance=NULL;  //static instance
CGlobalLog::CGlobalLog()
{
minimiumLogLevel = LOGLEVEL_INFO;
}

CGlobalLog::~CGlobalLog(void)
{
if(m_instance != NULL)
delete m_instance;
}

// this method is static
CGlobalLog& CGlobalLog::getInstance()
{

if(m_instance == NULL){
m_instance = new CGlobalLog();
}
return *m_instance;

}

其中 LOGLEVEL 是枚举,m_instance 是 CGlobalLog* CGlobalLog::m_instance。踪迹是:

WARNING: Visual Leak Detector detected memory leaks!
---------- Block 504 at 0x009B2290: 92 bytes ----------
Call Stack:
c:\users\ferran\directo\gameprojects2008\zeleste2d\src\log\globallog.cpp (26): LogSystem_v2.exe!glog::CGlobalLog::getInstance + 0x7 bytes
c:\users\ferran\directo\gameprojects2008\zeleste2d\src\log\globallog.cpp (235): LogSystem_v2.exe!glog::CGlobalLog::exposeAPI
c:\users\ferran\directo\gameprojects2008\games_and_samples\logsystem_v2\src\main.cpp (47): LogSystem_v2.exe!main + 0xB bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (586): LogSystem_v2.exe!__tmainCRTStartup + 0x19 bytes
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c (403): LogSystem_v2.exe!mainCRTStartup
0x767D339A (File and line number not available): kernel32.dll!BaseThreadInitThunk + 0x12 bytes
0x774D9ED2 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0x63 bytes
0x774D9EA5 (File and line number not available): ntdll.dll!RtlInitializeExceptionChain + 0x36 bytes
Data:
00 00 00 00 CD CD CD CD CD CD CD CD CD CD CD CD ........ ........
CD CD CD CD 28 23 9B 00 00 00 00 00 00 00 00 00 ....(#.. ........
CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD ........ ........
B0 23 9B 00 00 00 00 00 01 00 00 00 00 00 00 00 .#...... ........
CD CD CD CD 00 CD CD CD CD CD CD CD CD CD CD CD ........ ........
CD CD CD CD 00 00 00 00 0F 00 00 00 ........ ........

我找不到内存泄漏的任何原因....你能帮帮我吗?提前致谢

最佳答案

首先...您如何想象析构函数被调用?你在任何地方调用会破坏你的对象的东西吗?

在析构函数中再次调用删除指针将导致调用同一对象的另一个析构函数。所以你在这里有递归析构函数调用。由于它是单例类,您的调用可以简单地替换为 delete this;。您应该只将 m_instance 设置为 NULL,这样 getInstance 的另一个调用将不会引用释放的内存。

解决方案?编写静态方法“deleteInstance”来检查 m_instance 是否不为 null 并在 m_instance 上调用 delete 并将其设置回 null。然后你应该调用,即在主函数 CGlobalLog::deleteInstance(); 的末尾。这样你就可以抑制这种内存泄漏

关于c++ - 试图了解内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7423924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com