Is it bad style to design your simple C programs to allocate everything, or most everything, on the stack?
- 
        3It depends on what "everything" means.Khaled Alshaya– Khaled Alshaya2010-03-14 08:27:42 +00:00Commented Mar 14, 2010 at 8:27
- 
        1If you're going to do everything with locals and parameters, why are you using C in the first place? Use a functional language like ML, Haskell, Erlang, etc. instead.JUST MY correct OPINION– JUST MY correct OPINION2010-03-14 08:30:23 +00:00Commented Mar 14, 2010 at 8:30
- 
        As opposed to what, are you thinking of? Global variables, or data on the heap?Craig McQueen– Craig McQueen2010-03-14 08:37:27 +00:00Commented Mar 14, 2010 at 8:37
- 
        1@ttmrichter Maybe because C is a language that allows you to get things done? Anyway how your comment helps the OP?qrdl– qrdl2010-03-14 09:27:35 +00:00Commented Mar 14, 2010 at 9:27
- 
        @JT: A specific question will probably be more useful for you as this is rather vague. All absolutes are wrong, anyway.Roger Pate– Roger Pate2010-03-14 12:57:14 +00:00Commented Mar 14, 2010 at 12:57
5 Answers
It is bad style to use heap allocation if you don't really need it. Especially in simple programs.
5 Comments
Stack allocations are cheaper than heap allocations. Allocation and deallocation from stack is just simple counter increments and decrements on function (or to be more exact: scope) entry/exit. Heap allocations means finding a large enough memory block in a possibly fragmented address space. Because of that stack allocations are almost always preferable.
The main reasons for not using the stack are:
- The size needed is not known until runtime.
- A lot of memory (Megabytes) is needed; which can cause problems on systems where stack sizes typically are limited to two-digit numbers of Megabytes.
1 Comment
If we put emphasis on SIMPLE programs, as you stated, then no, it is not that bad :) You may also take a look at C99 variable-length arrays (here's a simple example: http://en.wikipedia.org/wiki/Variable-length_array).
1 Comment
The main advantage of the heap is that you can dynamically allocate on it. If you don't know the size of the variable you need : heap it.
If your program is simple, you might not need to allocate a variable on the heap; but the choice does not depend on the complexity of the program, it depends on the need you have of the variable. If you need to access/modify the variable all along your workflow, through several functions, then it's better on the heap. You'll free it when you won't need it anymore. If the variable is just an option structure or a counter, the stack is perfect for it.