I'm using MinGW with GCC 3.4.5 (mingw-special vista r3).
My C application uses a lot of stack so I was wondering is there any way I can tell programatically how much stack is remaining so I can cleanly handle the situation if I find that I'm about to run out.
If not what other ways would you work around the problem of potentially running out of stack space?
I've no idea what size of stack I'll start with so would need to identify that programatically also.
You can see how much stack space the application uses looking at /proc/PID/maps.
The stack area is typically 1 to 8Mb, and that's memory used by the compiler to store automatic variables (declared in functions), and function arguments. The heap is potentially all the remaining virtual memory space of your process, and what is used to allocate memory when using new or malloc.
You may need to increase the stack size if your program gets stack-overflow messages at runtime. You can also set the stack size by: Using the /STACK linker option. For more information, see /STACK (Stack allocations).
The default size of the main stack is about eight megabytes.
The getrusage function gets you the current usage . (see man getrusage
).
The getrlimit
in Linux would help fetching the stack size with the RLIMIT_STACK
parameter.
#include <sys/resource.h> int main (void) { struct rlimit limit; getrlimit (RLIMIT_STACK, &limit); printf ("\nStack Limit = %ld and %ld max\n", limit.rlim_cur, limit.rlim_max); }
Please give a look at man getrlimit
. The same information could be fetched by ulimit -s
or ulimit -a
stack size row. Also have a look at setrlimit
function which would allow to set the limits. But as the mentioned in the other answers if you need to adjust stack then probably you should re consider your design. If you want a big array why not take the memory from the heap ?
Taking the address of a local variable off the stack would work. Then in a more nested call you can subtract the address of another local to find the difference between them
size_t top_of_stack; void Main() { int x=0; top_of_stack = (size_t) &x; do_something_very_recursive(....) } size_t SizeOfStack() { int x=0; return top_of_stack - (size_t) &x; }
If you code is multi-threaded then you need to deal with storing the top_of_stack variable on a per-thread basis.
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