The purpose of this assignment is to provide experience with memory management, and with exception handling
int fibo(int n) { int k1, k2; if (n==1) { cout << "returning the result of fibo(1)"; return 1; } else if (n==2) { cout << "returning the result of fibo(2)"; return 1; } else { k1 = fibo(n-1); k2 = fibo(n-2); return k1 + k2; } }Assume that fibo is called from by an instruction of the form
fibo(5);Show with a drawing the situation on the stack at the moment in which the string "returning the result of fibo(1)" is printed for the first time. In particular, show the activation records for fibo present on the stack, with the parameters, locals, dynamic links, and their current values, if any.
class list { //Implementation of a list (only the methods relevant for this exercise) private: class element { public: int info; element* next; element(int x, element* e) { info = x; next = e; } } element* first; public: list() { first = NULL; } void insert(int x) { //Insert x at the beginning of the list first = new element(x,first); } };
void p() { list* l; l = new list(); l->insert(1); l->insert(2); l->insert(3); }; void q() { p(); cout << "executing q()"; };And a call
... q(); ...Show with a drawing the situation in the memory at the moment in which the string "executing q()" is printed. In particular, show all the memory leaks and dangling pointers (if any).
list* p() { list* l; l = new list(); l->insert(1); l->insert(2); l->insert(3); return l; }; void q() { list * l = p(); cout << "executing q()"; };
list* l; void p() { l = new list(); l->insert(1); l->insert(2); l->insert(3); delete l; }; void q() { p(); cout << "executing q()"; };
void p() { list* l; l = new list(); l->insert(1); l->insert(2); l->insert(3); delete l; }; void q() { p(); cout << "executing q()"; };
~list() { if (first != NULL) delete first; } ~element() { if (next != NULL) delete next; }
procedure p var x: int; procedure q procedure r(x:int) begin x := x-1; q end; // end body of r begin x := x-1; write(x); if x>1 then r(2) end; // end body of q begin x := 3; q end // end body of pNote that q is defined inside p, and r is defined inside q.