Answers/Solutions to Exercises in Chapter 10, Exercise 1

E1: Create as simple as possible a C or C++ based program exhibiting the orphaned allocation problem.

S1: How many times I have seen something like this:

....
....
// function DisplayMessage -----------------------------------
void DisplayMessage(int a1,float a2,char* tag)
{
  char *message;
  message=(char*)malloc(150+strlen(tag));
  // create the message
  ...
  // do something
  ...
  // 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,Interpret(tag));
  // display the message
  WriteLog(log,message);
}
....
....

Of course, the moment the function DisplayMessage() terminates, the allocated segmen is orphaned as message goes out of scope. And of course, usually the formatting is more complex, otherwise there would be no need to use sprintf().

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