I need to instantiate a char[16384] buffer before calling a c function. After the function returns I will read some parts of it and discard it.
Is it ok to allocate it on the stack or should I use the heap?
EDIT: I'll add some information. The code will run on several platforms, from PC to iPhone, where I guess the stack space will not be so big, but I have no idea about that.
It depends on your operating system. On Windows, the typical maximum size for a stack is 1MB, whereas it is 8MB on a typical modern Linux, although those values are adjustable in various ways.
The stack has a limited size, and consequently can only hold a limited amount of information. On Visual Studio for Windows, the default stack size is 1MB. With g++/Clang for Unix variants, it can be as large as 8MB. If the program tries to put too much information on the stack, stack overflow will result.
Stack allocation is cheap, heap allocation is expensive. Understanding the rules of escape analysis allows us to write more efficient code.
Because all threads in a process share the same address space, they have to divide it between them. And after the operating system has taken its part, there is "only" 2-3 GB left for an application. And that size is the limit for both the physical and the virtual memory, because there just aren't any more addresses.
Unless you're programming for embedded systems, code which might be running from a thread other than the main thread, or code which is called recursively, I would say 16k is well within the reasonable size you can allocate on the stack.
As for threads, if you're using POSIX threads and want your program to be portable, you can use the pthread_attr_setstacksize
interface to specify the amount of stack space your thread needs, and then as long as you know the calling patterns and over-estimate by a good margin in choosing the size, you can be sure it will be safe.
It's hard to give a definitive yes or no to this question because the answer is highly dependent on your environment and at what point in the program the function which allocates the memory is invoked.
Personally though if I saw this in a code review I'd raise a red flag. That's a lot of memory to be using for a stack based buffer. It may work today in the very specific place you're using it but what about tomorrow when you're called with a much bigger stack below you? Or when the customer hits a scenario you didn't consider?
But like I said it's scenario dependent and it may be just fine for your specific scenario. There's simply not enough detail in your question to say yes or no
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