Yesterday someone asked in the QQ group how to judge whether a C ++ object is on the stack, I searched on the internet, found this a CSDN post http://topic.csdn.net/t/20060124/10/4532966.html, unfortunately, it does not give a proper answer.
To answer this question, we actually need to know the starting address of the stack, and we know that the stack is actually a memory page with the same attributes, windows also has an API that allows us to query the page distribution of virtual memory. We can use the VirtualQuery API to obtain the starting address of the stack and then get the answer.
BOOL IsObjectOnStack (LPVOID pObject)
{
INT nStackValue (0 );
MEMORY_BASIC_INFORMATION mi = {0 };
DWORD dwRet = VirtualQuery (& nStackValue, & mi, sizeof (mi ));
If (dwRet> 0)
{
Return pObject> = mi. BaseAddress
& (DWORD) pObject <(DWORD) mi. BaseAddress + mi. RegionSize;
}
Return FALSE;
}
Int g_value = 10;
Int main (int argc, char * argv [])
{
Int nStackValue = 1;
Int * p = new int (10 );
BOOL bStackValue = IsObjectOnStack (& g_value); // false
BStackValue = IsObjectOnStack (& nStackValue); // true
BStackValue = IsObjectOnStack (p); // false
System ("pause ");
Return 0;
}
Of course, we know that each thread has its own stack, so the above method is feasible for thread 1 to query the stack object of thread 1, thread 2 can query the stack object page of thread 2, but thread 1 cannot query the stack object of thread 2. In the case of multithreading, we can calculate the starting addresses of all thread stacks and then make a unified judgment. Of course, with the establishment and destruction of threads, the stack itself is constantly changing.
I thought about how to determine whether the object is useful in our actual programming on the stack.
The above code passes the test in Windows. If there is any incorrect code, please correct it.
From thick and thin hair