Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Allocation in C

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

like image 999
JT. Avatar asked Mar 14 '10 08:03

JT.


People also ask

How do you allocate a stack?

On the Stacks page in the CloudFormation console, select the stack that you want to delete. The stack must be currently running. In the stack details pane, choose Delete. Select Delete stack when prompted.

Are C arrays allocated on the stack?

Unlike Java, C++ arrays can be allocated on the stack. Java arrays are a special type of object, hence they can only be dynamically allocated via "new" and therefore allocated on the heap.

Is malloc used for stack?

All variables allocated by malloc (or new in C++) is stored in heap memory. When malloc is called, the pointer that returns from malloc will always be a pointer to “heap memory”. All variables used as local variables – for example, when you just do int i = 0; – is stored on a function's stack.


2 Answers

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

like image 83
P Shved Avatar answered Sep 20 '22 17:09

P Shved


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.
like image 36
Anders Abel Avatar answered Sep 20 '22 17:09

Anders Abel