How to determine whether a C ++ object is on the stack

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.