Skip to content

2.2 Stack, Heap, Static, Code

This note serves the purpose of explaining how memory can be modeled as an array, where specific segments of the array mean something different. This will be important when talking about memory allocation [2.3 Memory Allocation] as well as pointers and arrays 2.3 Pointers and Arrays, Get back to toc CS61C or 2. C Programming

Memory

Our model of memory is an array. You can access elements of an array, but this time, the indexes are the addresses, and the elements are the actual data inside. In this class, we will use a bottom-up model, which you will understand in a bit. Here is a diagram to see this memory array.  400 Now, if we were to simply put memory where ever we wanted to, that would be a bit disorganized. Code that you write should also be in this memory array, so it might make sense to group the code segments nearby each other. How about variable declarations? When you open up functions, where should its location be stored? It seems like we need to group data together based on a couple of features. That leads us to Stack, Heap, Static, and Code: I'll first write a basic definition, and then write up a more complete definition at the bottom of this note.

  • Stack: local variables inside functions, located at the top of the stack, grows downwards
  • Heap: space requested for dynamic data via malloc or calloc. Resizes dynamically, grows upwards
  • Static/Data: variables declared outside functions, does not grow. Loaded when the program starts, though can be modified
  • Code: loaded when program starts. It is literally code.

One thing to note is that the stack grows down, and the heap grows up. We place the heap right above static/data (which is above code), and the stack begins at the very top. Here is a diagram showing relatively where memory would live.2.4.2 Memory Model.png Remember that memory is simply just stored in an array, with the addresses being the indices of this array. When you ask for the address of x using &x, you are saying "what index of this memory array is x stored at." Dereferencing a pointer to x is equivalent in saying "what value is stored at the address of x, or dereferencing_pointer = memory[address]. That is one way to interpret it. Therefore, a statement like int x = *ptr; is like saying int x = memory(ptr_address);.