Dynamic Memory Allocation


Task 1

Code

  1. #include<iostream>
  2. using namespace std;

  3. int main(){


  4.     int *p;
  5.     int num1 = 5;
  6.     int num2 = 8;
  7.     p = &num1; //store the address of num1 into p

  8.     *p = 10;

  9.     cout << endl;
  10.     cout<< "Line 1: &num 1 = " << &num1 << ", p = " << p << endl;
  11.     cout<< "Line 2: &num 1 = " << &num1 << ", *p = " << *p << endl << endl;
  12.     
  13.     p = &num2; //store the address of num2 into p
  14.     cout<< "Line 3: &num 2 = " << &num2 << ", p = " << p << endl; //line1 & line3 print different value
  15.     cout<< "Line 4: &num 2 = " << &num2 << ", *p = " << *p << endl << endl;

  16.     *p = 2 * (*p);

  17.     cout << "Line 5: num2 = " << num2 << " , *p = " << *p << endl << endl;

  18.     delete p;
  19.     return 0;
  20. }

Output

Line 1: &num 1 = 0x61ff08, p = 0x61ff08
Line 2: &num 1 = 0x61ff08, *p = 10

Line 3: &num 2 = 0x61ff04, p = 0x61ff04
Line 4: &num 2 = 0x61ff04, *p = 8

Line 5: num2 = 16 , *p = 16


Task 2

Code

  1. #include<iostream>
  2. using namespace std;

  3. int main(){
  4.     int *p;
  5.     int *q;

  6.     p = new int;
  7.     *p = 120;
  8.     cout << "Line 1: p = " << p << ", *p=" << *p << endl << endl;
  9.     
  10.     q = p;
  11.     cout << "Line 2: q = " << q << ", *q=" << *q << endl << endl;
  12.     
  13.     *q = 500;
  14.     cout << "Line 3: p = " << p << ", *p=" << *p << endl;
  15.     cout << "Line 4: q = " << q << ", *q=" << *q << endl << endl;

  16.     p = new int;
  17.     *p =180;
  18.     cout << "Line 5: p = " << p << ", *p=" << *p << endl;
  19.     cout << "Line 6: q = " << q << ", *q=" << *q << endl<< endl;
  20.     
  21.     delete q;
  22.     // cout << *q; //print garbage value
  23.     // cout << q; //print same address
  24.     q = NULL;
  25.     q = new int;
  26.     *q = 620;
  27.     cout << "Line 7: p = " << p << ", *p=" << *p << endl;
  28.     cout << "Line 8: q = " << q << ", *q=" << *q << endl<< endl;
  29.     
  30.     delete p;
  31.     delete q;
  32.     return 0;
  33. }

Output

Line 1: p = 0x1e6d88, *p=120

Line 2: q = 0x1e6d88, *q=120

Line 3: p = 0x1e6d88, *p=500
Line 4: q = 0x1e6d88, *q=500

Line 5: p = 0x1e6d98, *p=180
Line 6: q = 0x1e6d88, *q=500

Line 7: p = 0x1e6d98, *p=180
Line 8: q = 0x1e6d88, *q=620