//------------------------------------------------------------------- // Test.cpp //------------------------------------------------------------------- #include #include "Pointer_2.h" // Something "interesting" to point to... struct Node { int data; Pointer next; }; // Pointer can be passed by value and by reference void Something (Pointer pv, Pointer& pr) { pr = pv; } // Let's try some things! int main () { Pointer p1 = 0; Pointer p2 = p1, p3; Pointer q1, q2; int *bad; if (p1 == p2) { cout << "No surprise: p1 == p2\n\n"; } bad = new int; *bad = 49; cout << "*bad = " << *bad << "\n\n"; // No compile-time or run-time error here, but you can't // dereference p1 or you'll get an error (see next comment) p1 = bad; // Run-time error dereferencing dangling pointer // cout << "*p1 = " << *p1 << "\n"; // Compile-time error for mixed-mode assignment // bad = p1; New (p1); New (p2); p3 = p1; *p1 = 17; *p2 = -32; // Should see 17, -32, 17 cout << "*p1 = " << *p1 << "\n"; cout << "*p2 = " << *p2 << "\n"; cout << "*p3 = " << *p3 << "\n\n"; // Same as p3 = p2 Something (p2, p3); // Should see 17, -32, -32 cout << "*p1 = " << *p1 << "\n"; cout << "*p2 = " << *p2 << "\n"; cout << "*p3 = " << *p3 << "\n\n"; p3 = p1; Delete (p1); if (p1 == 0) { cout << "Surprise: p1 == 0\n\n"; } // Compile-time error for mixed-mode testing // if (p2 == 48600) // { // cout << "Surprise: p1 == 48600\n\n"; // } // Compile-time error for mixed-mode testing // if (p2 != 48600) // { // cout << "Surprise: p1 == 48600\n\n"; // } p1 = 0; if (p1 == 0) { cout << "No surprise: p1 == 0\n\n"; } // Run-time error dereferencing null pointer // cout << "*p1 = " << *p1 << "\n"; New (p1); *p1 = *p2 + 33; // Should see 1, -32 cout << "*p1 = " << *p1 << "\n"; cout << "*p2 = " << *p2 << "\n"; // Run-time error dereferencing dangling pointer // cout << "*p3 = " << *p3 << "\n\n"; New (p3); // Memory leak caused here, but not reported until later p2 = p1; // Should see 1, 1, then some arbitrary value, but no error cout << "*p1 = " << *p1 << "\n"; cout << "*p2 = " << *p2 << "\n"; cout << "*p3 = " << *p3 << "\n\n"; Delete (p1); // Run-time error deleting dangling pointer, with line number and // file name in error message // Delete (p2); // Compile-time error assigning non-null // p1 = 5745646; New (q1); q1->data = *p3; New (q1->next); q2 = q1->next; q2->data = 13; q2->next = 0; cout << "*q1 = " << "(" << q1->data << " (" << q1->next->data << "))\n"; cout << "q2->data = " << "(" << q2->data << ")\n\n"; // Memory leak caused here, but not reported until later q1 = q1->next; Delete (q2); // Compile-time error for mixed-mode assignment // p1 = q1; // Compile-time error for mixed-mode test // if (p1 == q1) // { // cout << "Surprise: p1 == q1\n\n"; // } // All memory leaks reported here Report_Storage_Allocation (); }