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?
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!).
If you are not using threads, or if you know that your code executes on the main stack, then
man getrlimit
)If you are using threads and could be executing on a thread other than main, see man pthread_getattr_np
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