// CS 1621 Fall 2005 // Handout demonstrating lifetime issues in C++ #include using namespace std; void tester() { static int stat = 0; // static variable int aut = 0; // stack-dynamic variable stat++; aut++; cout << "Stat. var: " << stat << " Auto. var: " << aut << endl; } int * getloc() { cout << "Allocating heap-dynamic variable. Will remain " << endl << "until explicit deallocation or end of program. " << endl; int * temp = new int; // temp is stack-dynamic variable, but return temp; // new int allocated is heap-dynamic } void loseloc(int * ptr) { cout << "About to deallocate heap-dynamic var." << endl; delete ptr; } int main() { for (int i = 1; i <= 5; i++) tester(); int * ptr = getloc(); // points to heap-dynamic variable *ptr = 100; // give value to location cout << "Heap-dynamic: " << ptr << " is " << *ptr << endl; // Heap dynamic variable's asserted lifetime is here loseloc(ptr); int * p2 = new int; cout << "Heap-dynamic: " << p2 << " is " << *p2 << endl; // However the delete call in C++ does not reset the value of the // pointer nor does it make the memory inaccessible. Thus, we can // still access the variable and the heap-dynamic memory even after // it has been deleted. This is called a "dangling reference". // Naturally, this is not wise and can lead to serious logic errors. // We will discuss this and other pointer issues in more detail when // we discuss memory management. *ptr = 250; cout << "Heap-dynamic: " << ptr << " is " << *ptr << endl; cout << "Heap-dynamic: " << p2 << " is " << *p2 << endl; }