Answers/Solutions to Exercises in Chapter 10, Exercise 4

E4: Create as simple as possible a C++ based program exhibiting the incorrect assignment problem and the correct it.

S4: We stay with the SmartCharPtr class from Exercise 2, but we modify the assignment (see the section of the code blocked off by /* **** ... */ part) and for "optical reasons we add the display statements for deallocation. The extra constructor SmartCharPtr(char* p) was added just for convenience of this illustration. Now the use of SmartCharPtr in the function main() will cause memory leaking -- see the output. The correction is to unblock the deallocation statements --- see the output.

class SmartCharPtr
{
public:
	SmartCharPtr() { ptr=0; owner=0; }
	SmartCharPtr(char* p) { ptr=(char*)malloc(strlen(p)+1); strcpy(ptr,p); owner=1; }
	~SmartCharPtr() { 
		if (ptr!=0 && owner) {
			cout << "deallocating string \"" << ptr << "\"\n" << flush;
			free((void*)ptr); 
		}
	}
	SmartCharPtr& operator=(SmartCharPtr& p) { // pass along the ownership
		/* ****
		if (ptr!=0) {
			cout << "deallocating string \"" << ptr << "\"\n" << flush;
			free((void*)ptr);
		} */
		ptr=p.ptr;
		owner=1;
		p.owner=0;
		return *this;
	}
	SmartCharPtr& operator=(char* p) {  // obtain the original ownership
		if (ptr!=0) {
			cout << "deallocating string \"" << ptr << "\"\n" << flush;
			free((void*)ptr);
		}
		ptr=p;
		owner=1;
		return *this;
	}
	operator char* () { return ptr; }
	friend ostream& operator<< (ostream& os,SmartCharPtr& p) { 
		os << '\"' << (char*)p << '\"'; return os; 
	}

protected:
	char* ptr;
	int owner;
};

int main()
{
	SmartCharPtr p, p1("1"), p2("2"), p3("3"), p4("4");
	p = p1;
	p = p2;
	p = p3;
	p = p4;
	return 0;
}

Output of the incorrect program:

deallocating string "4"

Output of the correct program:

deallocating string "1"
deallocating string "2"
deallocating string "3"
deallocating string "4"

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 10 Index