Is it possible to detect if a variable is in stack or heap based on its address?

Ken Thomases ken at codeweavers.com
Thu Feb 19 21:04:00 CST 2015


On Feb 19, 2015, at 7:53 PM, Bruno Jesus <00cpxxx at gmail.com> wrote:

> Hi all, the subject explains my needs. I would like to understand if
> printing %p of a pointer can help me check if it's in the stack or was
> allocated with some memory management functions.

Yes, usually:

    void* p = /* ... */;
    if ((char*)NtCurrentTeb()->Tib.StackLimit < (char*)p && (char*)p <= (char*)NtCurrentTeb()->Tib.StackBase)
        /* p is on the stack */;
    else
        /* p is not on the stack */

You could add some logging to dlls/ntdll/virtual.c:virtual_alloc_thread_stack() to record the range of each thread's stack.

> Something like:
> 
> void test()
> {
>  char stack[10], *heap = HeapAlloc(1234);
>  printf("%p %p", stack, heap);
> }
> 
> Can I be sure the first printed value is from stack and the second from heap?

Are you asking whether that function will print an address on the stack and an address from the heap?  Yes, it will.  Or are you asking if you can determine the difference between the two types of pointers just by inspection?  I don't think there are hard-and-fast rules, but with experience you can make a pretty good guess.  For example, at least on OS X (32-bit), addresses around 0x0033nnnn are typical of the first thread's stack.  You'll see a lot of those as arguments in a relay log because it's common to pass the address of a local in function calls.


> A plus question would be: Is it possible to know if an address is a
> const string?

Do you mean a *static* const string?  If it is, it will be from a mapped executable image.  A +virtual log will show the address ranges to which images are loaded.

-Ken




More information about the wine-devel mailing list