在帖子如何判斷一個C++對象是否在堆棧上 中, 又有人提出如何判斷一個C++對象是否在堆上。
其實我們可以參照那個帖子的方法類似實現,我們知道堆就是Heap,在windows上我們可以通過GetProcessHeaps來得到所有的堆句柄,而我們這裡只要知道Windows上的Heap Handle,其實就是堆的起始地址,就可以寫如下代碼了。
#include <iostream>
#include <windows.h>
using namespace std;
BOOL IsObjectOnHeap(LPVOID pObject)
{
BOOL bRet(FALSE);
DWORD dwHeaps = GetProcessHeaps(0, NULL);
LPHANDLE pHeaps = new HANDLE[dwHeaps];
if(pHeaps != NULL)
{
MEMORY_BASIC_INFORMATION mi = {0};
GetProcessHeaps(dwHeaps, pHeaps);
for(INT i=0; i<dwHeaps; ++i)
{
VirtualQuery((LPVOID)pHeaps[i], &mi, sizeof(mi));
if(pObject >= mi.BaseAddress
&& (DWORD)pObject < (DWORD)mi.BaseAddress + mi.RegionSize)
{
bRet = TRUE;
break;
}
}
}
delete []pHeaps;
return bRet;
}
int g_value = 10;
int main(int argc, char* argv[])
{
int nStackValue = 1;
int* pNew = new int(10);
int* pNewArray = new int[100];
static int static_value = 0;
cout << "g_value:" << IsObjectOnHeap(&g_value) << endl; //false
cout << "nStackValue:" << IsObjectOnHeap(&nStackValue) << endl; //false
cout << "static_value:" << IsObjectOnHeap(&static_value) << endl; //false
cout << "pNew:" << IsObjectOnHeap(pNew) << endl; //true
cout << "pNewArray:" << IsObjectOnHeap(pNewArray) << endl; //true
system("pause");
return 0;
}
以上代碼在Windows下測試通過(也只能在Windows上跑),如果有不正確的地方,歡迎指正。
摘自 厚積薄發