- Stack and Heap
- Pros and Cons of Stack and Heap
- Example Stack Program
- Example Heap Program
- Further Reading
- Detecting leaks easily
- Sparse Matrix / Sparse Array in C
- Example: A Sparse array in action
Stack and Heap
Remember the difference between Stack and Heap by remembering “The heap is a heap of a pain.”
Region of computer’s memory that stores temporary variables.
Memory is managed for you automatically.
Is a “LIFO” (Last in first out) data strucutre and is managed by the CPU.
Whenever a function declares a variable, it is pushed to the stack. Whenever the function exits, the variables are freed.
The heap is the region of memory that is not managed automatically.
You are responsible for freeing memory by using the free() function.
Pros and Cons of Stack and Heap
If you are dealing with relatively small variables that only need to exist as long as the function is running, then the stack is a good choice.
You should use the heap when you have to allocate a large block of memory that needs to be around for a long time.
Also if you want to use variables such as arrays and structs and would like to dynamically change their size, the heap is the way to go.
- Don’t have to worry about freeing memory you allocate. It is done for you.
- Variables can only be accessed locally
- Variables cannot be resized
Example Stack Program
- Variables can be accessed globally
- No limit on memory size
- Variables can be resized using realloc()
- (relatively) slower access
- no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
- you must manage memory (you’re in charge of allocating and freeing variables)
Example Heap Program
Stack vs. Heap - GribbleLab.org
Detecting leaks easily
To detect leaks, you can use the program, Valgrind.
valgrind --leak-check=full ./app
Sparse Matrix / Sparse Array in C
Sparse arrays are a cool way to hold data efficiently if you have a lot of zero values.
As an example, say you were creating a spreadsheet application. When the user opens the program, they might be presented with a 1000x1000 grid of cells for them to work with.
They are probably not going to use all of those cells. They might only use 100 cells in total for whatever they are doing.
So, you have two options:
- Create a multi-dimensional array to hold values for all of these cells. (
- Use a sparse array and only keep track of the cells your user is utilizing.
The second option is clearly the best. a 1000x1000 array is very large for a lot of zero values.
Example: A Sparse array in action
Before using this example, you may want to watch this video to better understand the method we are using.