0
 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?

2
  • 3
    You're invoking a UB, d is a dangling pointer
    – P0W
    Jul 14, 2014 at 4:42
  • Don't reinvent the wheel, use smart pointers. Jul 14, 2014 at 4:48

1 Answer 1

1

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.

3
  • Using the pointer after it has been deleted is UB also. [basic.stc.dynamic.deallocation]#4
    – M.M
    Jul 14, 2014 at 5:04
  • @MattMcNabb: Thanks. But formally-pedantic, "the pointer" is also a bit too vague: it's using the pointer value, after it's become invalid, that's UB. This includes copying it or comparing it. In contrast, in the case of a pointer variable, such as in the OP's code, the variable can be freely used, in particular it can be reused or nulled. Jul 14, 2014 at 5:20
  • Hoist by my own petard
    – M.M
    Jul 14, 2014 at 5:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.