Stack vs. Heap storage 01-30-2017, 05:39 PM
#1
In C and it's derivatives, (as well as most, if not all other languages) variables are stored in two separate ways. Static types (often called fixed or fixed length) are stored on the "stack", whereas dynamic storage (namely Objects and their properties in any OO language like C++, C#, Python, Ruby, etc) is handled by the heap. There are significant pros and cons to both systems, and it's good to know when to use one over the other when you're the one manually allocating all the memory.
The stack is a special place in memory that stores local variables (i.e. temporary; this is important) created by each function in your program (main() included). The stack is what's commonly called a LIFO structure, meaning "last in, first out", and it's managed entirely by the CPU, unless explicitly called upon.
Whenever a local variable is declared inside a function, said variable is pushed to the stack. When that function returns, all the variables pushed to the stack that the function created are freed from memory (you could also say they're deleted). When the space that a variable is taking up inside the stack is freed, that region immediately becomes available to other stack variables.
A quick demonstration of the stack is as follows:
The heap is another region of memory available to your program that is not automatically managed for you, and is not optimized by the CPU. It's often referred to as "free-floating" memory, and is larger than the stack. To allocate memory to the heap, you must do so manually with the standard library malloc() or calloc() functions. Once memory has been allocated to the heap, you are responsible for clearing it with the free() function (also stdlib) to avoid a memory leak.
Contrary to the stack, there is no size limit for variables stored in the heap except for the physical limit of the computer your program is running on. Heap variables, again unlike those in the stack, are passed by using pointers (which themselves are stored on the stack, and reference the value in the heap) instead of passing by value, as you would with a stack variable. In light of these points, heap storage is just a bit slower than stack. This difference in speed can appear negligible in small programs, but it can add up as programs get larger and more complex. Finally, once created, heap variables are accessible anywhere in your program, essentially putting them in a global scope.
A demonstration of heap storage is as follows. Obviously, this isn't the optimal way to write a program with this functionality, but it serves as a good demonstration:
Now that we've gone over what does what, we can list the pros and cons of both storage methods, as well as use cases.
Stack storage
Pros: automatically allocated and freed, faster, CPU optimized
Cons: limited variable size (varies by OS), variables are fixed size
Most commonly, you should use the stack when dealing with relatively small variables that only need to exist for the lifetime of a function. It's easier and faster, so you might as well utilize it.
Heap storage
Pros: global access to variables, only size limit is the system's physical capacity, variables can be resized
Cons: slightly slower read/write operations, manual allocation/deallocation
Again generally speaking, you should use the heap when you need to allocate a large block of memory (e.g. a large array, a struct with lots of members, etc) and/or you need to keep it around for a long period of time, or access it globally.
The Stack
The stack is a special place in memory that stores local variables (i.e. temporary; this is important) created by each function in your program (main() included). The stack is what's commonly called a LIFO structure, meaning "last in, first out", and it's managed entirely by the CPU, unless explicitly called upon.
Whenever a local variable is declared inside a function, said variable is pushed to the stack. When that function returns, all the variables pushed to the stack that the function created are freed from memory (you could also say they're deleted). When the space that a variable is taking up inside the stack is freed, that region immediately becomes available to other stack variables.
A quick demonstration of the stack is as follows:
Code:
#include <stdio.h> // io utilities
// function print the square of an integer, n
void print_square(int n){
// declare a variable sq_n of type int. Memory for
// sq_n is allocated for us in the stack
int sq_n;
// assign sq_n to n squared, filling the allocated memory
sq_n=n*n;
// print the value
printf("%i\n",sq_n);
// end of function; sq_n is deallocated
}
// main function
int main(){
// declare a variable num of type int, then fill the
// allocated memory with the int 7
int num=7;
// call the print_square() function using num
print_square(num);
// return from the function; num is deallocated
return 0;
}The Heap
The heap is another region of memory available to your program that is not automatically managed for you, and is not optimized by the CPU. It's often referred to as "free-floating" memory, and is larger than the stack. To allocate memory to the heap, you must do so manually with the standard library malloc() or calloc() functions. Once memory has been allocated to the heap, you are responsible for clearing it with the free() function (also stdlib) to avoid a memory leak.
Contrary to the stack, there is no size limit for variables stored in the heap except for the physical limit of the computer your program is running on. Heap variables, again unlike those in the stack, are passed by using pointers (which themselves are stored on the stack, and reference the value in the heap) instead of passing by value, as you would with a stack variable. In light of these points, heap storage is just a bit slower than stack. This difference in speed can appear negligible in small programs, but it can add up as programs get larger and more complex. Finally, once created, heap variables are accessible anywhere in your program, essentially putting them in a global scope.
A demonstration of heap storage is as follows. Obviously, this isn't the optimal way to write a program with this functionality, but it serves as a good demonstration:
Code:
#include <stdlib.h> // C standard library
#include <string.h> // string utilities
#include <stdio.h> // IO utilities
// declare an empty char pointer
char *str;
// function to reallocate heap memory to *str and
// copy a greeting to the address
void create_greeting(char *name){
// reallocate enough heap memory for the
// greeting and the name
realloc(str,sizeof(str)+sizeof(name));
// copy the formatted greeting to our heap memory
sprintf(str,"Hello, %s!",name);
// end of function; str is not deallocated because it's
// on the heap
}
// main function
int main(){
// allocate enough heap memory to our pointer for
// a greeting with no name (which is 8 characters)
str=(char*) malloc(8*sizeof(char));
// declare a *fixed* char array to hold a name; this is pushed
// to the stack automatically, because it has a fixed size
char name[]="Sinisterly";
// call the create_greeting() function with our name
create_greeting(name);
// print our greeting
printf("%s\n",str);
// manually free str from the heap
free(str);
// return from the function; our name string is freed
// from the stack
return 0;
}Pros, cons, and use cases
Now that we've gone over what does what, we can list the pros and cons of both storage methods, as well as use cases.
Stack storage
Pros: automatically allocated and freed, faster, CPU optimized
Cons: limited variable size (varies by OS), variables are fixed size
Most commonly, you should use the stack when dealing with relatively small variables that only need to exist for the lifetime of a function. It's easier and faster, so you might as well utilize it.
Heap storage
Pros: global access to variables, only size limit is the system's physical capacity, variables can be resized
Cons: slightly slower read/write operations, manual allocation/deallocation
Again generally speaking, you should use the heap when you need to allocate a large block of memory (e.g. a large array, a struct with lots of members, etc) and/or you need to keep it around for a long period of time, or access it globally.
It's often the outcasts, the iconoclasts ... those who have the least to lose because they
don't have much in the first place, who feel the new currents and ride them the farthest.
don't have much in the first place, who feel the new currents and ride them the farthest.















![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)
