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?
11
Upvotes
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.
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 :~)
2
u/[deleted] Mar 20 '26
[removed] — view removed comment