我可以在 C/C++ 中获得堆栈的限制吗?

Can I get the limits of the stack in C / C++?

我的问题非常简单明了:如果我有,例如分配给程序堆栈的 1MB RAM,我可以得到开始和结束的地址,或者开始和长度吗?

我正在使用 Visual Studio 2013.

你应该质疑你对堆栈布局的假设。

也许the stack doesn't have just one top and bottom

也许it has no fixed bottom at all

显然没有可移植的方法来查询不可移植的概念。

不过,在 Visual C++ 中,您可以使用 Win32 API,具体取决于 Windows 版本。

在Windows 8 很简单,只要调用GetCurrentThreadStackLimits

早期版本需要使用VirtualQueryEx and process the results somewhat. Getting one address in the stack is easy, just use & on a local variable. Then you need to find the limits of the reserved region that includes that address. Joe Duffy has written a blog post showing the details of finding the bottom address of the stack

GetCurrentThreadStackLimits 似乎可以满足您的需求,将堆栈的 lower/upper 边界转换为指针地址:

ULONG_PTR lowLimit;
ULONG_PTR highLimit;
GetCurrentThreadStackLimits(&lowLimit, &highLimit);

看起来它只适用于 Windows 8 和 Server 2012。

勾选MSDN

在 8 之前的Windows,自己实现 GetCurrentThreadStackLimits():

#include <windows.h>
#if _WIN32_WINNT < 0x0602
VOID WINAPI GetCurrentThreadStackLimits(LPVOID *StackLimit, LPVOID *StackBase)
{
    NT_TIB *tib = (NT_TIB *) NtCurrentTeb();
    *StackLimit = tib->StackLimit;
    *StackBase = tib->StackBase;
}
#endif