JT.
JT.

Reputation: 81

Stack Allocation in C

Is it bad style to design your simple C programs to allocate everything, or most everything, on the stack?

Upvotes: 8

Views: 606

Answers (5)

P Shved
P Shved

Reputation: 99364

It is bad style to use heap allocation if you don't really need it. Especially in simple programs.

Upvotes: 15

Opera
Opera

Reputation: 983

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.

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69280

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.

Upvotes: 3

Georg Schölly
Georg Schölly

Reputation: 126165

No. Unless you've got variables that have a non-fixed size. Such code could leave to a stack overflow quite fast.

Upvotes: 0

Roman Dmitrienko
Roman Dmitrienko

Reputation: 4235

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).

Upvotes: 1

Related Questions