【问题标题】:Setting memory on a custom heap在自定义堆上设置内存
【发布时间】:2014-06-08 22:54:20
【问题描述】:

是否可以从 HeapCreate() 中获取堆句柄并将所有可用内存设置为某个值?

我尝试按区域枚举堆并设置它,但我遇到访问冲突。

我基本上想将堆中的内存设置为可用于调试的自定义值,然后最终通过 HeapDestroy 销毁。

【问题讨论】:

  • 我认为这不是调试代码或修复内存泄漏的好方法...

标签: c++ heap-memory


【解决方案1】:

简短的回答是“不,你不能用特定的值填充堆”。

您可以使用调试版本包装您的堆访问函数,例如

// In some header file
#define HeapAlloc(a, b, c) MyHeapAlloc(a, b, c, __FILE__, __LINE__)
#define HeapFree(a, b, c) MyHeapFree(a, b, c, __FILE__, __LINE__)

... 

// In a separate source file:

#ifdef HeapAlloc
#undef HeapAlloc
#undef HeapFree
#endif

struct extra
{
    extra *next;
    size_t size;
    const char *file;
    int line;
};

extra* head;

LPVOID MyHeapAlloc(HANDLE heap, DWORD flags, SIZE_T size, const char *file, int line)
{
    LPVOID res = HeapAlloc(heap, flags, size + sizeof(extra));
    if (!res)
    {
        cout << "Allocation failed, called from " << file << ":" << line << endl;
        return 0;
    }

    extra *p = reinterpret_cast<extra*>(res);
    res = reinterpret_cast<void*>(&p[1]); 

    p->next = head;
    p->size = size;
    p->file = file;
    p->line = line;

    memset(res, 0xAA, size); 
    return res;
}

BOOL MyHeapFree(HANDLE heap, DWORD flags, LPVOID mem, const char *file, int line)
{
    extra *p = reinterpret_cast<extra*>(mem);
    p = reinterpret_cast<void*>(&p[-1]); 

    extra *q = head;
    extra *prev = 0;
    while(q)
    {
        if (reinterpret_cast<void*>(&q[1]) == mem)
        {
            break;
        }
        prev = q;
        q = next;
   }
   if (!q)
   {
       cout << "Attempt to free memory that wasn't allocated from " << file << ":" << line << endl;
       return false; 
   }

   /* Unlink q - if prev = NULL then it's the first one, so just move head */
   if (prev)
   {
      prev->next = q->next;
   }
   else
   {
      head = q->next;
   }

   memset(mem, 0xBB, q->size);
   return HeapFree(heap, flags, reinterpret_cast<void *>(q); 
}

我刚刚输入了所有内容,所以可能会有一些小错误,但希望它向您展示了一种处理内存分配的方法。在某些情况下,您可能必须将 extra 结构填充为 16 或 32 字节的倍数,以确保以下数据的对齐。当然,您可以随时转储head 指向的链表,以查看分配了什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2016-05-18
    • 2013-05-29
    • 1970-01-01
    相关资源
    最近更新 更多