如何找到写入释放的内存(堆损坏)?

问题描述 投票:2回答:1

我正在调试Visual Studio 2017下的多线程C ++应用程序。可以使用以下代码示例重现问题的类型

  int* i = new int();
  *i = 4;
  int* j = i;
  delete i;
  //perhaps some code or time passes
  *j = 5;//write to freed momory = possible heap corruption!!

我用built in heap checker来查找带有标志的问题类型:

 _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_DELAY_FREE_MEM_DF )

然后使用_ASSERTE(_CrtCheckMemory());试图缩小它 - 但只是得出结论它是在另一个线程。在检测到损坏时查看其他线程似乎只是做“正常”的事情而不是当时的应用程序代码。报告看起来像这样:

HEAP CORRUPTION DETECTED: on top of Free block at 0x00000214938B88D0.
CRT detected that the application wrote to a heap buffer that was freed.
DAMAGED located at 0x00000214938B88D0 is 120 bytes long.
Debug Assertion Failed!

每次120字节 - 但地址不同。 (检测到堆的方式是在检查堆时已经覆盖了0xdddddddd模式)找到分配或找到有问题的写入将是有帮助的。我曾尝试使用'gflags.exe',但我无法找到这种类型的损坏(据我所知,它主要用于查找缓冲区溢出)并且我以前没有使用此工具的经验。如果我能从地址中找到“唯一分配号码”,那么这也许会有所帮助。

c++ visual-studio-2017 heap-corruption
1个回答
0
投票

这是我用来跟踪它的代码。执行摘要:它将页面保留在虚拟内存中,而不是完全释放。这意味着尝试使用此类页面将失败。

DWORD PageSize = 0;

namespace {
  inline void SetPageSize()
  {
    if (!PageSize)
    {
      SYSTEM_INFO sysInfo;
      GetSystemInfo(&sysInfo);
      PageSize = sysInfo.dwPageSize;
    }
  }

  void* alloc_impl(size_t nSize) {
    SetPageSize();
    size_t Extra = nSize % PageSize;
    if (Extra != 0 || nSize == 0) {
      nSize = nSize + (PageSize - Extra);
    }
    void* res = VirtualAlloc(0, nSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
    if (!res) {
      DWORD errorMessageID = ::GetLastError();
      LPSTR messageBuffer = nullptr;
      size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

      throw std::bad_alloc{};
    }
    if (reinterpret_cast<size_t>(res) % PageSize != 0) {
      throw std::bad_alloc{};
    }

    return res;
  }

  void dealloc_impl(void* pPtr) {
    if (pPtr == nullptr) {
      return;
    }


    VirtualFree(pPtr, 0, MEM_DECOMMIT);


  }
}


void* operator new (size_t nSize)
{
  return alloc_impl(nSize);
}

void operator delete (void* pPtr)
{
  dealloc_impl(pPtr);
}
void *operator new[](std::size_t nSize) throw(std::bad_alloc)
{
  return alloc_impl(nSize);
}
void operator delete[](void *pPtr) throw()
{
  dealloc_impl(pPtr);
}
© www.soinside.com 2019 - 2024. All rights reserved.