Pointer pointing to Stack or Heap ??

Today on Code project some one posted a question like “Is there any way to find whether a pointer points to stack or heap”. Is there actually an API for the same??

Well windows dosen’t provide an API or a straight forward way to acomplish this. Any how we can find a pointer points to stack or heap by simple computations and ofcourse with the help of TIB( Thread Infomation Block – If you want to learn more about TIB, have a look to the Under The Hood article of Matt Pietrek ). In the Thread information block, there are two members, the “StackTop”( located at FS[4] ) and “StackBase” ( located at FS[8] ). The “StackTop” is the memory from which the stack started, and the “StackBase” is the stack location the program commits upto that point. So any object created on stack will have an address between this two pointers. So if we get a pointer just check whether the pointer falls between the above two memory locations. if it does, then it can be consider a pointer to some stack object. So here is my API to find whether the pointer points to stack or heap.

// This function will return true if the pointer points to stack. Other wise false
bool IsMemoryOnStack( LPVOID pVoid )
{
LPVOID dwStackTop = 0;
LPVOID dwStackLowCurrent = 0;
__asm
{
mov EAX, FS:[4]
mov dwStackTop, eax
mov EAX, FS:[8]
mov dwStackLowCurrent, eax
}
if( pVoid = dwStackLowCurrent )
{
// The memory lie between the stack top and stack commited.
return true;
}
// Pointer dosen’t point to the stack
return false;
}
Sample code that uses the above API..
void main()
{
int OnStack;
bool bOnStack = IsMemoryOnStack( &OnStack );// Returns true
int *pOnHeap = new int;
bOnStack = IsMemoryOnStack( pOnHeap );// Returns false
}
Advertisements

3 Responses to “Pointer pointing to Stack or Heap ??”

  1. It is totally platform dependent, isn’t it?

  2. also if i got the pointer from another application it must work uh?

  3. From Windows 95 to vista it will work..

    But this technique will not work if you pass an object created in stack of one thread to another thread and call this API from the second thread..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: