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 ... */
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With