How to detect if memory is from the stack? (not heap or a static variable)

Viewed 239

While there is no officially supported way to do this. Is there a way (on modern systems), to detect if a pointer is from the stack (stack of the caller for example).

Even if this is not going to work as part of actual code logic, it could help avoid errors in for the configurations that can detect it, eg:

void my_function(void *arg) {
    /* Only some configurations can do this (depending on compiler & arch). */
#if THE_MOONS_ALIGN
    assert(not_stack_memory(arg));
#endif

   /* ... actual logic ... */
}
1 Answers

Since stack and memory layout is not in the C standard, there is obviously no portable way to determine stack positions. However if you are compiling for a system managed by an operating system, there is good chance that the OS provides an API query the stack bounds.

On Windows it can be done as -

#include <windows.h>
struct _TEB {
        NT_TIB NtTib;
};


void *getStackBase(){
        return NtCurrentTeb()->NtTib.StackBase;
}
void *getStackLimit(){
        return NtCurrentTeb()->NtTib.StackLimit;
}

But be aware that this will give the stack bounds of the current thread, the variable could be situated on another thread's stack. In that case you will have to iterate over the thread handles and compare with each stack bound. You can use ThreadFirst and ThreadNext for that.

On Linux you can read the /proc/<pid>/maps file and look for the [stack] entry.

Related