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

时间:2015-02-24 23:12:40

标签: c++ c visual-c++

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

我使用的是Visual Studio 2013。

3 个答案:

答案 0 :(得分:30)

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

也许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并稍微处理结果。在堆栈中获取一个地址很简单,只需在局部变量上使用&即可。然后,您需要找到包含该地址的保留区域的限制。 Joe Duffy撰写了a blog post showing the details of finding the bottom address of the stack

答案 1 :(得分:9)

GetCurrentThreadStackLimits似乎正在寻找您正在寻找的东西,将堆栈的下/上边界变为指针地址:

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

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

检查MSDN

答案 2 :(得分:0)

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

Table 1           Table 2          Table 3  

Id Description   Id Description   Id   Description
--------------   ---------------  -------------------
1  A             33 XX            Y12  Algo
2  B             43 YY            M34  Something
3  C             23 ZZ            R77  Cosa
4  D             56 FF 
5  E
相关问题