/* Program 7.1.4 from C++ Programming Lecture notes  */

/* Author: Rob Miller and William Knottenbelt
   Program last changed: 28th September 2013    */

/* This program further illustrates the use of new and "NULL". */ 

#include <iostream>
#include <cstdlib>

using namespace std;

typedef int *IntPtrType; 

int main()
{
	IntPtrType ptr_a, ptr_b;

	/* have function throw exception if unsuccessful */
	try {
	        ptr_a = new int;
        } catch (bad_alloc) {
		cout << "Sorry, ran out of memory";
		exit(1);
	}

	/* have function return NULL if unsuccessful */
	ptr_a = new (nothrow) int;
	if (ptr_a == NULL)
	{
		cout << "Sorry, ran out of memory";
		exit(1);
	}
	*ptr_a = 4;
	ptr_b = ptr_a;
		
	cout << *ptr_a << " " << *ptr_b << "\n";
	
	ptr_b = new (nothrow) int;
	if (ptr_b == NULL)
	{
		cout << "Sorry, ran out of memory";
		exit(1);
	}
	*ptr_b = 7;
	
	cout << *ptr_a << " " << *ptr_b << "\n";

	*ptr_a = *ptr_b;
		
	cout << *ptr_a << " " << *ptr_b << "\n";
	
	delete ptr_a;
	ptr_a = NULL;
	ptr_b = NULL;
	
	if (ptr_a != NULL)
	{
		*ptr_a = 40;
		cout << "*ptr_a == " << *ptr_a;
	}
	else
	{
		cout << "Dangling pointer error - program terminated\n";
		exit(1);
	}
		
	return 0;
}
