是否可以从HeapCreate()获取堆句柄并将所有可用内存设置为某个值?
我尝试按区域枚举堆并按照这种方式设置堆,但是我遇到了访问冲突。
我基本上想要将堆中的内存设置为可用于调试的自定义值,然后通过HeapDestroy最终销毁它。
答案 0 :(得分:0)
简短的回答是"不,你不能用特定的值填充堆#34;。
您可以使用调试版本来包装堆访问函数,例如
// 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
指向的链接列表,以查看分配的内容。