Answers/Solutions to Exercises in Chapter 8, Exercise 5

E5: The following program is leaking memory. Find where and correct it.

#include <iostream>

extern "C" {
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
}

class A {
 public:
	char* string;
	A(char* s) { string = strdup(s); }
	A& operator=(const A& a) {
		string = a.string;
		return *this;
	}
};//end class A


int main()
{
	A a("hello");
	printf("%s\n",a.string);
	A b("good bye");
	printf("%s\n",b.string);
	b = a;
	printf("%s\n",b.string);

	return 0;
}

A5:  There are two problems with respect to memory leakage: there is no destructor, yet the construction involves dynamic memory allocation, hence when an object goes out of scope, the dynamic string inside that object will remain. But we would not see this problem on exhibited by this program, for objects a and b go out of scope when the program terminates. However, there is another memory leaking, and it is caused by assignment statement (like in Exercise 3 of this chapter): during assignment the internal pointer is just redirected, and the previous string it pointed to is not deallocated.

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