简体   繁体   中英

How can I find out how much space is left on stack of the current thread using vc++?

I am using VC++ 2012. I would like to be able to tell how much stack memory is available in current thread.

Quick search points to using malloc.h and stackavail() function, yet its not there in Visual C++ 2012. How do I achieve this in another way?

Example in question is this:

#include "stdafx.h"
#include <iostream>
#include <malloc.h>

using namespace std;

int _tmain()
{
    cout << "Available stack: " << stackavail() << std::endl;
}

This uses some stack but is thread-safe and doesn't require asm inline. I don't think those of us that need to track the stack need precision. Just a good estimate of what's available to prevent an overflow from occurring. We need to track it because we offer users the ability to create macros, scripts, expressions, etc.. that may use recursion or other services or needs. Every environment should be able to report stack availability even if it just uses all available memory so any recursion can be controlled.

size_t stackavail()
{
  // page range
  MEMORY_BASIC_INFORMATION mbi;                           
  // get range
  VirtualQuery((PVOID)&mbi, &mbi, sizeof(mbi));           
  // subtract from top (stack grows downward on win)
  return (UINT_PTR) &mbi-(UINT_PTR)mbi.AllocationBase;    
}

There is no such function as stackavail() in C++, though some compilers, such as "Open Watcom C++" provide it as an extension.

If you really need to know this information, use an OS-specific system call to figure it out.

Ok so these are my findings so far.

There is no easy one function way of checking stack space via vc++ on windows.

But I found an answer elsewhere .

size_t stackavail()
{
    static unsigned StackPtr;   // top of stack ptr
    __asm mov [StackPtr],esp    // mov pointer to top of stack
    static MEMORY_BASIC_INFORMATION mbi;        // page range
    VirtualQuery((PVOID)StackPtr,&mbi,sizeof(mbi)); // get range
    return StackPtr-(unsigned)mbi.AllocationBase;   // subtract from top (stack grows downward on win)
}

Additionally:

In windows/vc++ by default stack space is set at 1MB per thread. To set it higher for main() thread you have to compile via linker flag of /STACK:#### which is rounded to nearest 4. Ex: /STACK:2097152 for 2MB stack.

Hope this helps someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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