Programming Memory

Make sure to understand how this stuff you learn tie together with the ECE222 content on Chapter 5.

Actual implementation found in Memory Allocation for C++.

In the CS137 course, we model five sections of memory:

  1. Code: to store the program code/instructions in machine code (machine-readable), done during compiling
  2. Read-Only Data: to store the global constants
  3. Global Data: to store the global variables and available throughout the entire execution of the program.
  4. Heap: used to dynamically allocate memory (see below)
  5. Stack: used to store local variables and return addresses to manage function calls, etc. Each function call creates a stack frame. The stack grows toward lower addresses.

From CS138:

Tip

Most of the time, just pass the pointer, not a copy, as this uses up less memory.

Dynamic Memory Allocation

We use the heap to dynamically allocation memory. Heap is great to:

  • resize arrays when they are full
  • store global data variable to the whole program

Warning

You must get rid of the global data variables by the end of the program (else marmoset will give you 0 because it detects memory leak).

Why do we dynamically allocate memory? At the beginning of the program, we don’t know how much memory we need. The heap has much more memory than the stack, but it is slower.

Serendipity: So this is what they mean by “Stack Overflow”? When the stack can no longer hold any data.

Stack vs. Heap

(Runtime) Stack

The run-time stack manages the storage needs (local variables + parameters) for each pending function call.

Summary from CS137:

  • Scratch space for a thread of execution
  • Each thread gets a stack
  • Elements are ordered (new elements stacked on older elements)
  • Faster since allocating/deallocating memory is very fast

Heap

The heap (aka “freestore”) stores all dynamically-allocated “objects” .

  • Memory set aside for dynamic allocation
  • The memory stored in heap is dynamically allocated via a call to new or malloc
  • When this allocated memory is no longer needed, we can deallocate it (can be “returned” to OS and possibly reused)

Summary from CS137:

  • Typically only 1 heap for an entire application
  • Entries might be unordered and chaotic
  • Usually slower since need a lookup table for each element (i.e. more bookkeeping)