Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to determine how much space is available on the stack?

Tags:

c++

I'm architecting a small software engine and I'd like to make expensive use of the stack for rapid iterations of large number sets. But then it occurred to me that this might be a bad idea since the stack isn't as large a memory store as the heap. But I am attracted to the stack's speed and lack of dynamic allocation coding practices.

Is there a way to find out how far I can push the stack on a given platform? I am looking mainly at mobile devices but the issue could come up on any platform.

like image 207
johnbakers Avatar asked Jun 22 '13 12:06

johnbakers


People also ask

Is there any way to determine the available stack space at run time?

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).

How is stack space calculated?

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.

How much stack memory is available?

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.

How big is the stack size?

In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm. Most compilers including Visual Studio let you specify the stack size.


1 Answers

On *nix, use getrlimit:

   RLIMIT_STACK
          The maximum size of the process stack, in bytes.  Upon
          reaching this limit, a SIGSEGV signal is generated.  To handle
          this signal, a process must employ an alternate signal stack
          (sigaltstack(2)).

On Windows, use VirtualQuery:

For the first call, pass it the address of any value on the stack to get the base address and size, in bytes, of the committed stack space. On an x86 machine where the stack grows downwards, subtract the size from the base address and VirtualQuery again: this will give you the size of the space reserved for the stack (assuming you're not precisely on the limit of stack size at the time). Summing the two naturally gives you the total stack size.

There is no platform-independent method since stack size is left to the implementation and host system logically - on an embedded mini-SOC there are less resources to distribute than on a 128GB RAM server. You can however influence the stack size of a specific thread on all OS'es as well with API-specific calls.

like image 143
Niels Keurentjes Avatar answered Oct 16 '22 02:10

Niels Keurentjes