neharika
neharika

Reputation: 75

memory is not getting freed up which was allocated before there arises an exception in constructor

 class book
   {
     int*d;
     char ch;
    public:book()
       {
          try
            {
              d=new int(23);
               throw 'A';
                ch='B';
             }
          catch(char c)
             {
                 delete d;
                cout<<"caught exception in constructor\n";
             }
       }
         void show()
             {
                cout<<*d<<endl<<ch;
              }
   };
  main()
  {
      book b;
      b.show();
  }

when there arises an exception in a constructor,we should free the memory allocated to avoid memory leak.But in the above code,i am trying to free the allocated memory,even then it is showing the correct answer i.e value of *d is shown as 23.why is it so?

Upvotes: 0

Views: 51

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

Using the pointer's referent after it's been deleted, is Undefined Behavior.

It's not unnatural that the value has not been cleared or altered. But it would not be unnatural if was cleared or altered, either. And it would not be unnatural if the program crashed, whatever.


In other news...

Throwing a char or other basic value may cause trouble, or at least prevent logging of a suitable message. Ordinarily the expectation is an exception derived from std::exception, e.g. std::runtime_error or std::system_error.

Catching an exception in a constructor is OK in itself, but not throwing when the constructor fails is an invitation to disaster – the instantiating code will be left with an invalid object.

To facilitate cleanup in a constructor that fails, use smart pointers, standard collection classes, or custom RAII (cleanup in destructors of suitably defined types).

Declaring main without a result type is invalid in C++, which has never supported implicit int.

Regarding style, the public:book() looks like an access specifier applied to a single item, as in Java and C#. In C++ an access specifier starts a region with a given access. Thus it's unnatural to combine it visually with a single something.

Upvotes: 1

Related Questions