c++ - 处理破坏堆的对象

标签 c++ heap-memory heap-corruption fault-tolerant-heap

在我的应用程序中,我正在创建一个非常像这样的对象:

connect() {
  mVHTGlove = new vhtGlove(params);
}

一旦我要关闭应用程序,我就调用它:

disconnect() {
  if (mVHTGlove) 
    delete mVHTGlove;
}

此调用始终会触发断点并显示以下消息:

Windows has triggered a breakpoint in DesignerDynD.exe.

This may be due to a corruption of the heap, which indicates a bug in DesignerDynD.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while DesignerDynD.exe has focus.

The output window may have more diagnostic information.

我无法修改 vhtGlove 类来修复堆栈损坏,因为它是仅以头文件、lib 文件和 dll 形式提供的外部库。

有什么方法可以干净地使用这个类吗?


**** 编辑::: 我试图将事情精简到最低限度,但我得到了相同的结果......这里有完整的代码。

#include "vhandtk/vhtCyberGlove.h"
#include "vhandtk/vhtIOConn.h"
#include "vhandtk/vhtBaseException.h"

using namespace std;

int main(int argc, char* argv[])
{
   vhtCyberGlove* testGlove = NULL;

   vhtIOConn gloveAddress("cyberglove", "localhost", "12345", "com1", "115200");
   try
   {
      testGlove = new vhtCyberGlove(&gloveAddress,false);

      if (testGlove->connect())
         cout << "Glove connected successfully" << endl;
      else
      {
         throw vhtBaseException("testGlove()->connect() returned false.");
      }

      if (testGlove->disconnect())
      {
         cout << "Glove disconnected successfully" << endl;
      }
      else 
      {
         throw vhtBaseException("testGlove()->disconnect() returned false.");
      }

   }
   catch (vhtBaseException *e)
   {
      cout << "Error with gloves: " << e << endl;
      system("pause");
      exit(0);
   }

   delete testGlove;

   return 0;
}

删除手套时仍然崩溃。


编辑 #2::如果我只是分配和删除 vhtCyber​​Glove 的一个实例,它也会崩溃。

int main(int argc, char* argv[])
{
   vhtCyberGlove* testGlove = NULL;
   vhtIOConn gloveAddress("cyberglove", "localhost", "12345", "com1", "115200");
   testGlove = new vhtCyberGlove(&gloveAddress,false);
   delete testGlove; //<<crash!
   return 0;
}

有什么想法吗?

谢谢!

JC

最佳答案

一种可能是 mVHTGlove 没有被初始化为 0。如果在没有调用 connect 的情况下调用了 disconnect,那么您将尝试释放垃圾指针。繁荣。

另一种可能性是您实际上在那一点之前破坏了堆栈,但这是破坏实际导致崩溃的地方。检查这一点的一个好方法是尽可能多地注释掉代码并仍然让程序运行,然后查看是否仍然出现损坏。如果您不这样做,请慢慢带回一些代码,直到您看到它回来。


一些进一步的想法(在你的编辑之后)。

您可能会检查 API 是否没有自己的内存管理调用,而不是期望您手动“新建”和“删除”对象。我这样说的原因是,当一些内存在 DLL 内部管理而另一些内存在外部管理时,我看到一些 DLL 存在看起来很像这样的问题。

关于c++ - 处理破坏堆的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1166348/

相关文章:

c - C 动态分配如何与链接器一起定义堆位置

c++ - &在这段代码中的作用是什么?

c++ - .begin 左边必须有类/结构/union

c++ - 即使正确设置,我的 consoleHandler 也无法处理 CTRL+C

eclipse - *以编程方式*监控 Eclipse 插件堆大小

c - realloc() 触发异常

c++ - 在 C++ 中使用 map 而不是 array 来保护在数组边界之外的搜索?

c - 链表删除导致 Free Heap block ........ 被释放后在 .... 处修改

c++ - 自定义 vector 类中的堆损坏错误

c - 使用 malloc、struct 和 char * 的堆损坏