Answers/Solutions to Exercises in Chapter 10, Exercise 3

E3: Create as simple as possible a C++ based program exhibiting the insufficient destructor problem and then correct it.

S3: Consider the sample solution for Exercise 2, but with the destructor for SmartCharPtr missing (see below). This will make the memory leak again, for when q goes out of scope when DisplayMessage() terminates, the string is not deallocated. For the correction, see Exercise 2.

class SmartCharPtr
{
public:
	SmartCharPtr() { ptr=0; owner=0; }
	SmartCharPtr& operator=(SmartCharPtr& p) { // pass along the ownership
		if (ptr!=0) free((void*)ptr);
		ptr=p.ptr;
		owner=1;
		p.owner=0;
		return *this;
	}
	SmartCharPtr& operator=(char* p) {  // obtain the original ownership
		if (ptr!=0) free((void*)ptr);
		ptr=p;
		owner=1;
		return *this;
	}
	operator char* () { return ptr; }

protected:
	char* ptr;
	int owner;
};

// function DisplayMessage -----------------------------------
void DisplayMessage(int a1,float a2,char* tag)
{
  char *message;
  SmartCharPtr p, q;
  message=(char*)malloc(150+strlen(tag));
  // create the message
  if (tag!=0) 
	  p=Interpret(tag);  // ownership passed from Interpret() to p
  // do something
  q = p;                     // ownership passed from p to q
  // do something
  if (tag==0)
    sprintf(message,"there are %d items with price %f without a tag\n",a1,a2);
  else
    sprintf(message,"there are %d items with price %f with tag %s\n",a1,a2,(char*)q);
  // display the message
  WriteLog(log,message);
  free((void*)message);
}
// when DisplayMessage() terminates, both p and q go out of scope, p will be destroyed without
// deallocating ptr as it is not owner, q will be destroyed with deallocating ptr, as it is owner
// function Interpret ------------------------------------------
SmartCharPtr& Interpret(char *tag)
{
  char *buff;
  static SmartCharPtr p;
  buff=(char*)malloc(150+strlen(global_text));
  if (strcmp(tag,"tag1")==0)
     strcpy(buff,"Red tag without dot");
  else if (strcmp(tag,"tag2")==0)
     strcpy(buff,"Green tag with dot");
  strcat(buff,global_text);
  p = buff;
  return p;
} 

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