Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of remaining stack until a stack overflow occurs

On Linux, using C, assume I have an dynamically determined n naming the number of elements I have to store in an array (int my_array[n]) just for a short period of time, say, one function call, whereby the called function only uses little memory (some hundred bytes).

Mostly n is little, some tenths. But sometimes n may be big, as much as 1000 or 1'000'000.

How do I calculate, whether my stack can hold n*o + p bytes without overflowing?

Basically: How much bytes are there left on my stack?

like image 383
kay Avatar asked Dec 03 '11 04:12

kay


2 Answers

Indeed, the checking available stack question gives good answer.

But a more pragmatic answer is: don't allocate big data on the call stack.

In your case, you could handle differently the case when n<100 (and then allocating on the stack, perhaps thru alloca, makes sense) and the case when n>=100 (then, allocate on the heap with malloc (or calloc) and don't forget to free it). Make the threshold 100 a #define-d constant.

A typical call frame on the call stack should be, on current laptops or desktops, a few kilobytes at most (and preferably less if you have recursion or threads). The total stack space is ordinarily at most a few megabytes (and sometimes much less: inside the kernel, stacks are typically 4Kbytes each!).

like image 153
Basile Starynkevitch Avatar answered Sep 23 '22 04:09

Basile Starynkevitch


If you are not using threads, or if you know that your code executes on the main stack, then

  1. Record current stack pointer when entering main
  2. In your routine, get current stack limit (see man getrlimit)
  3. Compare difference between current stack pointer and the one recorded in step 1 with the limit from step 2.

If you are using threads and could be executing on a thread other than main, see man pthread_getattr_np

like image 21
Employed Russian Avatar answered Sep 21 '22 04:09

Employed Russian