Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking available stack size in C

Tags:

c

stack

mingw

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.

like image 472
Paul Hargreaves Avatar asked Sep 10 '08 11:09

Paul Hargreaves


People also ask

How do I know my current stack size?

You can see how much stack space the application uses looking at /proc/PID/maps.

How much stack memory is available in C?

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.

How do you specify stack size?

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

How large is C stack?

The default size of the main stack is about eight megabytes.


2 Answers

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 ?

like image 148
phoxis Avatar answered Sep 30 '22 12:09

phoxis


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.

like image 32
Rob Walker Avatar answered Sep 30 '22 12:09

Rob Walker