Checking available stack size in C Checking available stack size in C c c

Checking available stack size in C


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.


check if your compiler supports stackavail()