In the post how to tell if a C + + object is on the stack, it is also suggested how to tell if a C + + object is on the heap.
In fact, we can refer to that post method similar implementation, we know that heap is heap, on Windows we can getprocessheaps to get all the heap handle, and we here just know the heap Handle on Windows, is actually the start address of the heap, you can write the following code.
#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;
}
The above code is tested under Windows (and can only run on Windows), if there is an incorrect place, please correct it.
Note: The above decision on whether the object is on the heap should be wrong, because heap memory is not contiguous memory, internal is through a similar list of structure to implement the,<< software debugging >> in the relevant introduction, you can also through the WinDbg!address command to view the memory distribution
Http://www.cppblog.com/weiym/archive/2012/05/12/174657.html
In fact, to determine whether an object is on the heap or on the stack is not so complex, because the default stack address is fixed, the stack space up to 1MB, if more than 1MB will cause the stack depletion exception, so just to determine if on the stack, just to see if there is no in this address range
How to tell if a C + + object is on the heap (get all the heaps by getprocessheaps and then compare with the object address), with many wonderful comments