www.digitalmars.com Home | Search | C & C++ | D | DMDScript | News Groups | index | prev | next
Archives

D Programming
D
D.gnu
digitalmars.D
digitalmars.D.bugs
digitalmars.D.dtl
digitalmars.D.dwt
digitalmars.D.announce
digitalmars.D.learn
digitalmars.D.debugger

C/C++ Programming
c++
c++.announce
c++.atl
c++.beta
c++.chat
c++.command-line
c++.dos
c++.dos.16-bits
c++.dos.32-bits
c++.idde
c++.mfc
c++.rtl
c++.stl
c++.stl.hp
c++.stl.port
c++.stl.sgi
c++.stlsoft
c++.windows
c++.windows.16-bits
c++.windows.32-bits
c++.wxwindows

digitalmars.empire
digitalmars.DMDScript

c++ - Crash in exception handler

↑ ↓ ← Heinz Saathoff <hsaat despammed.com> writes:
Hello,

this code below will crash after successfully catching the thrown Error. 
It will run ok if the "delete[] str" in the destructor or class Error is 
commented out.
I compiled this example as
   dmc -Ae Ex.cpp

- Heinz


-------------- code start ------------------
#include <string.h>
#include <stdio.h>

class Error {
public:
   Error(const char *m) {
      str = strcpy(new char[1+strlen(m)], m);
   }
   virtual ~Error() { delete[] str;}
   const char *msg() {return str;}
protected:
   char *str;
};

void Func()
{  try {
      throw Error("Test Error");
   }
   catch(Error &e) {
      fprintf(stderr, "Error is %s\n", e.msg());
   }
}//Func

int main()
{  Func();
   return 0;
} //main
-------------- code end ---------------------
Dec 20 2005
↑ ↓ → Heinz Saathoff <hsaat despammed.com> writes:
Hello,

I have to blame myself a bit. I got a hint from PC-lint that Error did 
not have a copy constructor and assignment operator. First I added the 
assignment operator and the program still crashes. Then I also added the 
copy constructor and voila, program doesn't crash anymore!

- Heinz


Modified running code:

-------------- code start ------------------
#include <string.h>
#include <stdio.h>

class Error {
public:
   Error(const char *m) {
      str = strcpy(new char[1+strlen(m)], m);
   }
   Error(const Error &e) {
      str = strcpy(new char[1+strlen(e.str)], e.str);
   }
   virtual ~Error() { delete[] str;}

   Error &operator=(const Error &e) {
      delete[] str;
      str = strcpy(new char[1+strlen(e.str)], e.str);
      return *this;
   }

   const char *msg() {return str;}
protected:
   char *str;
};

void Func()
{  try {
      throw Error("Test Error");
   }
   catch(Error &e) {
      fprintf(stderr, "Error is %s\n", e.msg());
   }
}//Func

int main()
{  Func();
   return 0;
} //main
-------------- code end --------------------
Dec 20 2005