Skip to main content
Logo image

Section 18.2 The Stack

The stack is a special region in your computer’s memory that stores temporary variables created by each function (and this includes the main() function). The word "stack" actually more accurately describes the way the storage of variables is organized.
We won’t really go into details here, but a few things of interest are:
  • Every time a function (including main()) declares a new variable, it is "pushed" onto the stack.
  • When a function terminates, all of the variables pushed onto the stack by that function, are deleted (also called "freed"). Once a stack variable is freed, that particular space in memory becomes available for other stack variables and you no longer have access to the freed variables.
Later on we will learn about another way to find space in memory for things you’d like to store (the so-called "heap"). The advantage of using the stack to store variables is that you do not have to manage this memory: the CPU is in charge.
 

If you cannot see this codecast, please click here.