简体   繁体   English

如何检测内存是否来自堆栈? (不是堆或静态变量)

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

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 ... */
}

Since stack and memory layout is not in the C standard, there is obviously no portable way to determine stack positions. 由于堆栈和内存布局不在C标准中,因此显然没有可移植的方法来确定堆栈位置。 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. 但是,如果要编译由操作系统管理的系统,则操作系统很有可能提供堆栈边界的API查询。

On Windows it can be done as - 在Windows上,它可以作为 -

#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. 您可以使用ThreadFirstThreadNext

On Linux you can read the /proc/<pid>/maps file and look for the [stack] entry. 在Linux上,您可以读取/proc/<pid>/maps文件并查找[stack]条目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM