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;
}
Count the number of complete strings, multiply by 8 (since "STACK---" is 8 bytes long), and you have the number of bytes of remaining stack space.
It depends on your operating system. On Windows, the typical maximum size for a stack is 1MB, whereas it is 8MB on a typical modern Linux, although those values are adjustable in various ways.
You can check how much stack space you are really using by checking how far %esp is from the upper limit of the stack area on smaps (as the stack grows down).
The default thread stack size is 160KB in 32-bit mode and 320KB in 64-bit mode. If you create a lot of threads, you might run out of stack space.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With