The Stack

Let's learn about the stack and how it's useful in allocating memory for functions.

So far we have seen how to declare basic type variables such as int, double, etc, and complex types such as arrays and structures. The way we have been declaring such variables, so far, puts these variables on the stack.

What is the stack?

It’s a special region of your computer’s memory that stores temporary variables created by each function (including the main function). The stack is a LIFO data structureLIFO that’s managed and optimized by the CPU quite closely.

Every time a function declares a new variable, it is “pushed” onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other use.

Memory management with stack

The advantage of using the stack to store variables, is that memory is managed for us. We don’t have to allocate memory by hand, or free it once we don’t need it any more.

What’s more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.

Stack variables are local in nature

A key to understanding the stack is the notion that when a function exits, all of its variables are removed or “popped” off the stack (and hence lost forever). Thus, stack variables are local to that function.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy