c++ - Crash in exception handler
- Heinz Saathoff (33/33) Dec 20 2005 Hello,
- Heinz Saathoff (41/41) Dec 20 2005 Hello,
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
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