CMPSC 461: Programming Language Concepts Assignment 4 Solutions
CMPSC 461: Programming Language Concepts Assignment 4 Solution Problem 1 [5pt] Give an example in a programming language that you’re familiar with in which a variable is alive but not in scope. Solution: One example in C. After the function exists, the object that C links to is no longer in scope, but it is alive. 1 void foo() 2 { 3 myClass* C = new myClass(); 4 return; 5 } Problem 2 [10pt] Consider the following class instances in a C++ program: 1 static myClass A; 2 3 int main() 4 { 5 myClass *B = foo(); 6 ... 7 delete B; 8 return 0; 9 } 10 11 myClass* foo() 12 { 13 myClass* C = new myClass(); 14 myClass D; 15 return C; 16 } a) (4pt) What is the storage allocation (static/stack/heap) for the objects associated with A, C and D? How about the storage for the pointer B? Solution: A is static allocated, C is heap allocated, and D is stack allocated. The pointer B is stack allocated. b) (6pt) Consider one execution of the program above. The execution trace, a sequence of program statements executed at run time, of this program is 7 8 For each object associated with A, C, and D, write down its lifetime (use a subset of execution trace, e.g., 13 14 15 to represent the lifetime). Solution: Lifetime of A: 5 13
Written for
Document information
- Uploaded on
- September 25, 2023
- Number of pages
- 4
- Written in
- 2023/2024
- Type
- Exam (elaborations)
- Contains
- Questions & answers
Subjects
-
cmpsc 461 programming language concepts assignmen
Also available in package deal