CPSC170A
Fundamentals of Computer Science II

Lab 21

Dynamic Memory

Trace Dynamic Memory

For each of the follwing, what will be printed when it is run. If it produces a compile or runtime error, just put error. If prints something, but it can’t be predicted, put unknown.

  1. int main() {
      int* p = new int(1);
      int* q = new int;
      *q = *p + 1;
      std::cout << *p << " " << *q << std::endl;
      delete p;
      delete q;
      return 0;
    }
  2. int main() {
      int a[2] = {1, 2};
      int* b = new int[2];
      b[0] = a[0];
      b[1] = a[1];
      a = {1, 2, 3};
      delete[] b;
      b = new int[3];
      b[0] = a[0];
      b[1] = a[1];
      b[2] = a[3];
      std::cout << b[0] <<  " " << b[1] << " " << b[2] << std::endl;
      delete[] b;
      return 0;
    }
  3. int* func(int i) {
      return &i;
    }
    
    int main() {
      int* p = func(1);
      int* q = func(2);
      std::cout << *p << " " << *q << std::endl;
      return 0;
    }
  4. struct Point {
      int x, y;
      Point();
      Point(int x, int y);
    };
    
    Point::Point() {
      this->x = 0;
      this->y = 0;
    }
    
    Point::Point(int x, int y) {
      this->x = x;
      this->y = y;
    }
    
    int main() {
      Point* p = new Point;
      Point* q = new Point(1, 2);
      std::cout << p->x << " " << p->y << std::endl;
      std::cout << q->x << " " << q->y << std::endl;
      delete p;
      delete q;
      return 0;
    }


Expanding Array

Write the C++ function that repeatedly prompts the user to enter a positive number. When the user enters a negative number the program should print the average of all the previously entered positive numbers. Because the number of numbers to be entered by the user is not known, the program should use dynamic memory to store the numbers entered by the user. Do this by doing the following every time a new number is entered by the user:

  1. Allocate a new array that is one larger than the existing array.
  2. Copy all of the values from the existing array into the new array.
  3. Deallocate the memory for the existing array.
  4. Update the existing array’s pointer to reference the new array.
  5. Add the new number to the array.

This program should not use the Vector class.