The Stack
There is another part of memory called the stack that is separate from the heap. The reason for the names heap and stack has to do with how we visualize them. The heap is a giant heaping mess of objects, and we use pointers to remember where those objects are stored within the heap. The stack, on the other hand, can be visualized as a physical stack of frames.
When a method (or function) is executed, it allocates a chunk of memory from the stack. This chunk of memory is called a frame, and it 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 the main function, the frame for main is put at the bottom of the stack. When main calls another method (or function), the frame for that method is added to the top of the stack. Of course, that method could call another method, and so on, until we have a towering stack of frames. Then, as each method or function finishes, its frame is “popped off” the stack and destroyed. If the method is called again, a brand new frame will be allocated and put on the stack.
For example, in your RandomPossessions
application, the main function runs BNRItem’s randomItem method,
which in turn runs BNRItem’s alloc method. The stack would look like Figure 3.2. Notice that main’s frame stays alive while the other methods are executing
because it has not yet finished executing.
Figure 3.2 Stack growing and shrinking
Recall that the randomItem method runs inside of a loop in the main function. So with every iteration, the stack grows and shrinks as frames are pushed on and popped off the stack.