How to find write to freed memory (heap corruption)?

时间:2019-04-04 19:04:24

标签: c++ visual-studio-2017 heap-corruption

I am debugging a multi-threaded C++ application under Visual Studio 2017. The type of problem can be reproduced with the following code sample

  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!!

I've used the 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',但是我找不到这种类型的损坏(因为我了解它主要是为了查找缓冲区溢出而设计的),并且我以前没有使用此工具的经验。 如果我可以从地址中找到“唯一分配号”,那也可能会有帮助。

1 个答案:

答案 0 :(得分: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);
}
相关问题