Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

stack-memory

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 ... */
}
like image 297
ideasman42 Avatar asked Sep 20 '17 06:09

ideasman42


People also ask

How can you tell if a memory is allocated in stack or heap?

Stack memory is allocated in a contiguous block whereas Heap memory is allocated in any random order. Stack doesn't require to de-allocate variables whereas in Heap de-allocation is needed.

Is static memory in stack or heap?

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.

What is the difference between heap memory and stack memory and static memory?

Stack and Heap memory are allocated to an application by the Java Virtual Machine (JVM). Stack Memory in Java is used for the execution of a thread and static memory allocation. Stack memory contains method specific primitive values and references to objects in the heap that are getting referred from the method.

What variables obtain memory from the stack?

The variables allocated on the stack are called stack variables, or automatic variables. Since the stack memory of a function gets deallocated after the function returns, there is no guarantee that the value stored in those area will stay the same.


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.

like image 167
Ajay Brahmakshatriya Avatar answered Oct 13 '22 00:10

Ajay Brahmakshatriya