Advanced Program Trace: Objects and the Heap

Symbol Table

The translator, e.g., your Python interpreter, tracks the variables in a program using a symbol table. The symbol table maps variables to where they are stored in memory. The symbol table is NOT part of the computer's memory-- it is part of the interpreter/compiler only.

Computer Memory


    Code


    
Run-time stack



    Heap

The heap stores dynamically allocated data, that is allocated as a program runs. This includes space for:

  •     objects created with object creation statements
  •     lists
  •     strings

Strings

The data for a string is stored on the heap, using 2 bytes for each character and another byte for the end-of-string character. Consider the following:

    str = "abc"

The variable str is allocated four bytes on the run-time stack (in an activation record). The 'value' of str would be an address-- it would point to some location on the heap holding the values "abc".

Lists

A list's elements are stored on the heap. Consider the following:

    list = [4,5,3.2]

The variable list is allocated four bytes on the run-time stack. The elements 4,5, and 3.2 are stored somewhere on the heap, along with some additional space allocated to the list.

Object creation

When an instance of some class is created, the system allocates enough space on the heap for all the data members of the class. Consider class Person:

    class Person:
        def __init__(self,name, age):
            self.name=name
            self.age=age
        #...
        
When a person is created, e.g.,

    joe = Person("joe smith",32)

the system allocates 4 bytes for name which points to "joe smith" and 4 bytes for the age 32:

Advanced Tracing

To explore memory management, we'll trace some Python programs using some simplified assumptions about memory. Specifically, we'll say that the stack begins at address 1000 with the activation for the main code. We'll say that the heap begins at address 3000, and we'll say that both the stack and the heap will grow downward. We'll assume lists are allocated 100 bytes on initialization.

Instructor Trace: show the symbol table and memory that would exist if the following program were run:

class Person:
    def __init__(self,name, age):
            self.name=name
            self.age=age

list = ["abc",12]
x=45
p = Person("dave",21)
list.append(p)









In-Class Assignment: show the symbol table and memory that would exist if the following program were run:

class Person:
   
def init(self,name, age):
            self.name=name
            self.age=age

str = "Ralph"
p = Person("john,65)
list=[]
list.append(str)
list.append(86)
p2 = Person("bo",32)
p.name="henry"

Recent site activity