Computer programs store variables in memory and may accomplish this task in either of two ways: by pushing them onto stack memory or by adding them to a pre-allocated space in heap memory. Several factors determine which of these two methods is used.
Programs typically store variables that are local in scope (that is, variables that are created by and exclusive to a certain function) in a section of the computer's memory called the stack. In the stack, data behaves much like a stack of paper; new data can only be added on top of any data that came before it, and old data can only be removed from the top of the stack downward. The removal of a variable stored in the stack occurs as soon as the function that created it finishes and exits. This method of storing variables is extremely efficient because the location of variables relevant to the current process is always known.
By contrast, heap memory does not follow the same orderly process of storing variables. As its name suggests, the storage location for a variable stored in the heap is dynamic. When heap is used, a certain amount of free memory is dedicated exclusively for the program's use. Then, the variable is stored in that reserved section of memory and a reference to its address, called a pointer, is created so that it can be retrieved later. Heap is used when variables need to persist even after a function that uses it exits.