Previous Page
Next Page

How Computer Memory is Organized

Computers use memory to hold programs being executed, and the data that these programs use. In order to understand the differences between value and reference types, it is helpful to understand how data is organized in memory.

Operating systems and runtimes (such as the common language runtime) frequently divide the memory used for holding data into two separate chunks, each of which is managed in a distinct manner. These two chunks of memory are traditionally called the stack and the heap. The stack and the heap serve very different purposes:

The names stack and heap come from the way in which the runtime organizes memory:

Using the Stack and the Heap

Now let's examine what happens when the following Method is called:

void Method(int param) 
{ 
    Circle c; 
    c = new Circle(param); 
    ... 
}

Suppose the value passed into param is the value 42. A piece of memory (just enough for an int) is allocated from the stack, and initialized with the value 42. Inside the method, another piece of memory big enough to hold a reference is also allocated from the stack, but left uninitialized (this is for the Circle variable, c). Next, another piece of memory big enough for a Circle object is allocated from the heap. This is what the new keyword does. The Circle constructor runs to convert this raw heap memory into a Circle object. A reference to this Circle object is stored in the variable c. The following graphic illustrates the situation:

Graphic

At this point, you should note two things:

  1. Although the object itself is stored on the heap, the reference to the object (variable c) is stored on the stack.

  2. Heap memory is not infinite. If heap memory is exhausted, the new operator will throw an OutOfMemoryException and the object will not be created.

NOTE
The Circle constructor could also throw an exception. If it does, the memory allocated to the Circle object will be reclaimed and the value returned by the constructor will be a null reference.

When the function ends, the parameters and local variables go out of scope. The memory acquired for c and the memory acquired for param is automatically released back to the stack. The runtime notes that the Circle object is no longer referenced, and at some point in the future will arrange for its memory to be reclaimed by the heap (see Chapter 13).


Previous Page
Next Page