Programming Languages:
Homework 2
Purpose:
This homework
assignment asks you to think about the binding of storage to variables, and
distinguish three ways of memory storage and binding in C++.
Download
and extract this zip file to get the C++ source
program storage.cpp
(and the entire Visual C++ project) under the storage folder. Examine the C++ code to understand what is going on
in the experiments, run the program to see the result of a few experiments, and
in particular pay attention to observe the outputs of memory addresses bound to
the variables in different function call contenxts.
Answer the following questions based on the code and your understanding of the
class lectures and the related reading.
Questions:
1. In the function testFunc(), is a fixed virtual memory storage bound to the variable numberOfTimesCalled once for all throughout the entire program execution? If so, when is this binding fixed? Could the value of numberOfTimesCalled retained from one function call to the next function call? Why or why not.
2. In the function testFunc(), is a fixed virtual memory storage bound to the local variable x once for all throughout the entire program execution? If not, when does the binding of the memory storage to the local variable x happen? Could different storage be bound to this local variable x at different point of time? Why or why not? Could the value of x retained from one function call to the next function call? Why or why not.
3. Is a fixed virtual memory storage bound to the global variable gX once for all throughout the entire program execution? If not, when does the binding of the memory storage to the global variable gX happen? Could different storage be bound to this global variable x at different point of time? Why or why not?
4. Among the variables declared globally or locally in functions in this program, what variables have static storage bound to them (i.e. fixed virtual memory address throughout the program execution)? What variables have stack storage bound to them (i.e. new memory storage allocated and bound to them in the context of some function calls involving them)? What variables provide ways to access heap storage?
5. What is wrong with the code in Part 3 and what happens when you run it?
6. Write a program with an infinite loop that keeps allocating heap memory by calling new int[1000] without ever freeing the memory back. Run the program and observe what happens to the overall system performance.
7. Write a program and try to declare a very large global array int Global[size1] outside the main function and a very large global array int Loca[size2] inside the main function. How big can size1 be and how big can size2 be? Are they the same?
8. Explain informally about our thoughts about the pros and cons of different ways of managing memory (i.e. using static storage, stack storage, heap storage respectively) in C++?