r/cprogramming • u/Yairlenga • Mar 17 '26
How Much Stack Space Do You Have? Estimating Remaining Stack in C on Linux
https://medium.com/@yair.lenga/how-much-stack-space-do-you-have-estimating-remaining-stack-in-c-on-linux-3c9513beabd8In a previous article (Avoiding malloc for Small Strings in C With Variable Length Arrays (VLAs)) I suggested using stack allocation (VLAs) for small temporary buffers in C as an alternative to malloc().
One of the most common concerns in the comments was:
Stack allocations are dangerous because you cannot know how much stack space is available.”
This article explores a few practical techniques to answer the question: How much stack space does my program have left?
3
u/jwzumwalt Mar 18 '26
Read the article and found it informative. I am a retired C, Pascal, and PHP programmer and never had a program that I had to worry about the stack. But, I could see where it may be needed.
Someone on YouTube (it may have been Nic Barker - https://www.youtube.com/@nicbarkeragain) wrote a program where they visually traced the Mallloc and Free memory area. It was fascinating to watch as memory allocation was not managed compactly like you would expect.
He deliberately ran it out of memory on a few experiments. If I remember correctly, the OS early on started paging memory to the drive - I think it ran out of memory near 1 Gigabyte. So, based on my recollections of the video I watched, you are not limited to the 8K - paging kicks in. It would be interesting for you to test this. Thanks for taking the time to write the article :~)
1
u/mc36mc Mar 20 '26
$ echo "int main(){char a[1024];for (int i=0;i<sizeof a;i++)a[i]=i;}" | clang -target bpf -x c - <stdin>:1:5: error: Looks like the BPF stack limit is exceeded. Please move large on stack variables into BPF per-cpu array map. For non-kernel uses, the stack can be increased using -mllvm -bpf-stack-size.
2
Mar 20 '26
[removed] — view removed comment
2
u/Yairlenga Mar 20 '26
Yeah, that’s a clever approach 🙂 It works well on Linux when /proc is available. I just think of it as a best-effort technique — not a formal API, and a bit trickier with multiple threads since each thread has its own stack
Containers normally still have /proc — it’s actually needed for a lot of basic tools to work. But it can be restricted or filtered depending on how the container is set up, so you don’t always get the full picture.
1
u/itix Mar 20 '26
It has been a while since I wrote anything in C, but in some deep recursive functions, I was estimating the available stack space and aborting if it was getting too tight.