Is it just a "bad manner" to allocate large buffers in a stack (if the stack has enough capacity)? I mean allocating 300-500 KB objects with an 8 MB stack in Linux systems. Or it may cause any errors? Also, are there any guidelines on how to use stack memory?
Asked
Active
Viewed 602 times
3
-
2It depends on your use case (which we don't know). Rule of thumb: the larger the buffer the worse it is allocating it on the stack. – Jabberwocky Nov 18 '21 at 14:49
-
If its not enough you can change process resource limit, so 8 MB is just default limit but not hard coded. You can change stack size with this command: `ulimit -s 8192`. – foragerDev Nov 18 '21 at 14:50
-
3It is dangerous. A function does not live in a vacuum, it is being called by other functions, which might have their own stack-allocated variables, and in turn can be called by some other functions. It can even be a part of some recursive algorithm. The stack allocations are...stacked. – Eugene Sh. Nov 18 '21 at 14:53
-
Yes, there are discussions and guidelines, and infinite opinions. Like this one for example: [when to use stack or heap memory](https://stackoverflow.com/questions/102009/when-is-it-best-to-use-the-stack-instead-of-the-heap-and-vice-versa) – ryyker Nov 18 '21 at 14:54
-
My personal limit for buffers on stack in 1 kiB. – prapin Nov 18 '21 at 15:34
2 Answers
1
There's no hard rule regarding the size of stack-allocated variables.
As a general rule, I prefer to not have any stack allocations larger than about 10KB. That way running out of stack space will be much less likely to be an issue. Anything bigger than that should be dynamically allocated, then freed when no longer needed.

dbush
- 205,898
- 23
- 218
- 273
1
Yes, it's a bad manner. Objects of that size is to be dynamic allocated (or be static). No exceptions.
What if your program one day is to be used on a system with less default stack size? For instance windows.. then you "eat" half the stack in a single call.

Support Ukraine
- 42,271
- 4
- 38
- 63