Answers/Solutions to Exercises in Chapter 8, Exercise 3

E3: What is wrong with the following class and what kind of problems it may cause during the execution?

class A {
	public:
		A() { string = 0; }
		A(char* x) { 
			string = new char[strlen(x)+1];
			strcpy(string,x);
		}
		~A() { if (string) free(string); }
		A& operator= (const A& a) {
			string = new char[strlen(a.string)+1];
			strcpy(string,a.string);
			return *this;
		}
};

A3: A recipe for memory leakage! The old string inside a is not deallocated! Every time we have an assuagement in the program: A& a, b; .... a = b; the dynamic string inside a is "forgotten" and a new copy of the string inside b is created.

class A {
	public:
		A() { string = 0; }
		A(char* x) { 
			string = new char[strlen(x)+1];
			strcpy(string,x);
		}
		~A() { if (string) free(string); }
		A& operator= (const A& a) {
                        if (string) delete[] string;            // correction
			string = new char[strlen(a.string)+1];
			strcpy(string,a.string);
			return *this;
		}
};

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