VS2010报告DLL中的静态类的假内存泄漏 [英] VS2010 reports false memory leaks for static classes in a DLL

查看:348
本文介绍了VS2010报告DLL中的静态类的假内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Visual Studio DLL调用ITK时出现内存泄漏的后续问题

我将问题改进到最简单的例子。

I refined the problem to the simplest example.

struct A
  {
  public:
    A()
      {
      mp_data = new int(0x42);
      }
    ~A()
      {
      delete mp_data;
      }
    int* mp_data;
  };

A a;

当在DLL中定义这样的全局类时,Visual Studio调试CRT报告mp_data泄露应用程序关闭。

When such a global class is defined in a DLL, Visual Studio debug CRT reports that mp_data is leaked on application shutdown. Does anybody know a workaround except disabling leak reporting?

推荐答案

如果你正在调用 _CrtDumpMemoryLeaks code>将在 _CrtDumpMemoryLeaks() mp_data

If you are calling _CrtDumpMemoryLeaks() at the end of the main function the behaviour is expected, since mp_data will be deleted after _CrtDumpMemoryLeaks() was called.

您需要在静态对象的最后一个析构函数之后调用 _CrtDumpMemoryLeaks()被调用(或者在内存释放后的最后一个析构函数中),如果你不想看到这些泄漏(相当困难的任务,我不想试试)。

You would need to call _CrtDumpMemoryLeaks() after the last destructor of you static objects has been called (or rather in the last destructor after the memory has been freed) if you dont want to see these leaks (quite difficult task, i wouldnt try it).

更清洁的方法是在堆上分配所有的静态对象(在 main 的开头),并在 main ,然后你可以调用 _CrtDumpMemoryLeaks(),不会看到任何内存泄漏。

The cleaner approach is to allocate all your static objects on the heap instead (at the beginning of main), and deallocate them at the end of main, and then you can call _CrtDumpMemoryLeaks() and wont see any memory leaks.

具有构造函数和析构函数的FYI静态对象被认为是坏的,因为它们被构造/分解的顺序不是确定性的,并且因为该静态对象经常引入不易被调试的错误。

FYI static objects with constructors and destructors are considered bad anyways, because the order in which they are constructed/desctructed is not deterministic, and because of that static objects often introduce bugs which cant be debugged easily.

编辑Andrey的评论:
您可以尝试通过调用 _CrtDumpMemoryLeaks
的自动调用=http://msdn.microsoft.com/en-us/library/5at7yxcs%28v=vs.71%29.aspx =nofollow> _ CrtSetDbgFlag 取消设置 _CRTDBG_LEAK_CHECK_DF 标志。如果这样工作,你可以在它的析构函数中添加一个调用 _CrtDumpMemoryLeaks()的静态对象。要确保此对象最后被销毁,您可以使用 #pragma init_seg(编译器)指令

Edit regarding Andrey's comment: You could try to deactivate the automatic call to _CrtDumpMemoryLeaks by calling _CrtSetDbgFlag to unset the _CRTDBG_LEAK_CHECK_DF flag. If that works, you can add a static object which calls _CrtDumpMemoryLeaks() in its destructor. To make sure that this object is destructed last, you can use the #pragma init_seg(compiler) directive.

没有线索,如果这将工作...除此之外,所有其他解决方案将很可能要求您修改ITK库(这应该是可能的,它是一个开源库?)。

No clue if this will work ... other than that, all other solutions will most likely require you to modify the ITK library (which should be possible, it's a open source library after all?!).

这篇关于VS2010报告DLL中的静态类的假内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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