I'm trying to delete the dynamic memory in the destructor of user defined exception which is allocated in the constructor of user defined exception. But I get core dump stating that the memory is freed twice:
user1@ubuntu:~/practice$ ./a.out
Test Exception
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000000f0b0b0 ***
Aborted (core dumped)
I suspect the MyException
object is going out of scope two times, one in myfunc()
and another in main's catch
block which is causing this issue. But I could not figure out how to free the memory in this case. Can you help me?
Here's the code:
#include<iostream>
#include<exception>
#include<cstring>
using namespace std;
class MyException: public exception
{
char *msg;
public:
MyException(){}
MyException(char *str)
{
msg = new char[strlen(str)+1];
strcpy(msg,str);
}
char *what()
{
return msg;
}
~MyException() throw()
{
delete msg;
}
};
class A
{
public:
void myfunc() throw(MyException)
{
throw MyException((char*)"Test Exception");
}
};
int main()
{
try
{
A ob;
ob.myfunc();
}
catch (MyException e)
{
cout<<e.what()<<endl;
}
}