Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack variables vs. Heap variables

Tags:

c

Am I correct in thinking that:

char *buff[500]; 

... creates a stack variable, and:

char *buff = (char *)malloc(500); 

... creates a heap variable?

If that's correct, when and why would you use heap variables over stack variables and vice versa. I understand the stack is faster is there anything else.

One last question, is the main function a stack frame on the stack?

like image 867
Jack Harvin Avatar asked Mar 10 '11 11:03

Jack Harvin


People also ask

Are variables on heap or stack?

Stack and a Heap ? Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.

What is the difference between stack and heap?

The Heap Space contains all objects are created, but Stack contains any reference to those objects. Objects stored in the Heap can be accessed throughout the application. Primitive local variables are only accessed the Stack Memory blocks that contain their methods.

When should I use the heap vs the stack?

Use the stack when your variable will not be used after the current function returns. Use the heap when the data in the variable is needed beyond the lifetime of the current function.

What variables are stored in stack and heap memory?

stack : stores local variables. heap : dynamic memory for programmer to allocate. data : stores global variables, separated into initialized and uninitialized. text : stores the code being executed.


1 Answers

Yes, first one creates an array of char pointers in the stack, about 500*4 bytes and second one allocates 500 chars in the heap and points a stack char ptr to them.

Allocating in the stack is easy and fast, but stack is limited, heap is slower but much bigger. Apart from that, stack allocated values are "deleted" once you leave the scope, so it is very good for small local values like primitive variables.

If you allocate too much in the stack you might run out of stack and die, main as all the functions you execute has a stack frame in the stack and all the local variables to the function are stored there, so going too deep into function calling might get you into a stackoverflow as well.

In general is a good rule of thumb to allocate anything that you use often and is bigger than a hundred bytes in the heap, and small variables and pointers in the stack.

like image 123
Arkaitz Jimenez Avatar answered Oct 07 '22 11:10

Arkaitz Jimenez