This chapter is from the book

The Stack

When a method (or function) is executed, a chunk of memory is allocated from a part of memory called the stack. This chunk of memory is called a frame, and the frame stores the values for variables declared inside the method. A variable declared inside a method is called a local variable.

When an application launches and runs main(), the frame for main() is put on the stack. When main() calls another method (or function), the frame for that method is put on top of the stack. Of course, that method could call another method, and so on, until you have a towering stack of frames. As each method or function finishes, its frame is “popped off” the top of the stack and destroyed. If the method is called again, a new frame will be allocated and put on the stack.

For example, in the RandomItems application, the main function runs BNRItem's randomItem method, which in turn runs alloc. The stack would look like Figure 3.1. Notice that main()'s frame stays alive while the other methods are executingbecause it has not yet finished executing.