与Visual Studio确定堆栈空间 [英] Determining Stack Space with Visual Studio

查看:166
本文介绍了与Visual Studio确定堆栈空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Visual Studio 2005编程用C我有一个多线程程序,但在这里,这不是特别重要。

I'm programming in C in Visual Studio 2005. I have a multi-threaded program, but that's not especially important here.

我如何确定(大约)我的线程的堆栈使用多少空间?

How can I determine (approximately) how much stack space my threads use?

我正打算使用的设置堆栈存储器的一些predetermined价值的技术,说0xDEADBEEF,运行程序很长一段时间,暂停该程序,调查堆栈。

The technique I was planning to use is setting the stack memory to some predetermined value, say 0xDEADBEEF, running the program for a long time, pausing the program, and investigating the stack.

我如何阅读和使用Visual Studio写堆栈内存?

How do I read and write stack memory with Visual Studio?

编辑:见,例如, <如何确定最大堆栈用量。 / A>有关嵌入式系统这个问题举行会谈,但在这里我试图确定在普通PC上的答案。

See, for example, "How to determine maximum stack usage." That question talks about an embedded system, but here I'm trying to determine the answer on a regular PC.

推荐答案

Windows不会立即提交堆栈存储器;相反,它保留了它的地址空间,而当它被访问提交它页逐页。阅读此页面获得更多信息。

Windows does not commit the stack memory immediately; instead, it reserves the address space for it, and commits it page-by-page when it is accessed. Read this page for more info.

其结果,堆栈地址空间由三个相邻区的

As a result, stack address space consists of three contiguous regions:


  • 保留但未提交内存,并且可以用于堆栈增长(但从来没有访问);

  • 保护页,这是从来没有访问过没有,并提供访问时触发堆栈增长;

  • 这是有史以来的线程访问
  • 提交内存,即堆栈存储器。

这使我们能够构建一个获得堆栈大小(以页面大小的粒度)的函数:

This allows us to construct a function that obtains stack size (with page size granularity):

static size_t GetStackUsage()
{
    MEMORY_BASIC_INFORMATION mbi;
    VirtualQuery(&mbi, &mbi, sizeof(mbi));
    // now mbi.AllocationBase = reserved stack memory base address

    VirtualQuery(mbi.AllocationBase, &mbi, sizeof(mbi));
    // now (mbi.BaseAddress, mbi.RegionSize) describe reserved (uncommitted) portion of the stack
    // skip it

    VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi));
    // now (mbi.BaseAddress, mbi.RegionSize) describe the guard page
    // skip it

    VirtualQuery((char*)mbi.BaseAddress + mbi.RegionSize, &mbi, sizeof(mbi));
    // now (mbi.BaseAddress, mbi.RegionSize) describe the committed (i.e. accessed) portion of the stack

    return mbi.RegionSize;
}

有一点要考虑:的CreateThread 允许指定初始堆栈提交大小(通过 dwStackSize 参数,当 STACK_SIZE_PARAM_IS_A_RESERVATION 标志没有被设置)。如果该参数不为零,只有当栈的使用变得比 dwStackSize 值时我们的函数将返回正确的值。

One thing to consider: CreateThread allows to specify initial stack commit size (via dwStackSize parameter, when STACK_SIZE_PARAM_IS_A_RESERVATION flag is not set). If this parameter is nonzero, our function will return correct value only when stack usage becomes greater than dwStackSize value.

这篇关于与Visual Studio确定堆栈空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆