PDA

View Full Version : Application crashes when I delete the character pointer array



arunkumaraymuo1
12th February 2013, 06:31
try
{
char *testarr = new char[15];
QString strVal1="Test";
QByteArray br = strVal1.toUtf8();
testarr = br.data();


delete[] testarr; //Why my application crashes here.
}
catch(...)
{
QMessageBox::information(0, "", "Error");
}




I have two questions

1) Why my above program crashes when I call delete[] testarr; ?
2) Why the catch block doesnot hadle that exception ?

I am using Qt creator 4.8 in ubuntu OS

Lesiok
12th February 2013, 07:57
Because You are deleting internal data of QByteArray.
I think line 6 should be :
strcpy(testarr,br.data());

arunkumaraymuo1
12th February 2013, 08:20
Thank you very much,that solved the issue. I have one another doubt too, How I can protect from application crash with try catch when any exception occure.


Because You are deleting internal data of QByteArray.
I think line 6 should be :
strcpy(testarr,br.data());

MarekR22
12th February 2013, 12:14
Your code has lots of problems:

char *testarr = new char[15];
QString strVal1="Test";
QByteArray br = strVal1.toUtf8(); // why? you could use simply QByteArray br("Test"); avoiding some unnecessary conversions.
testarr = br.data(); // here you have memory leak, you are loosing touch with block you allocated in first line, by overriding it with value form QByteArray

delete[] testarr; // now you are deleting something what is owned by `br`

d_stranz
12th February 2013, 21:26
How I can protect from application crash with try catch when any exception occur.

The error in your code did not result in a C++ exception; it was most likely a segmentation fault caused when the QByteArray instance on the stack went out of scope and tried to delete the internal memory you had already deleted in line 6. Try/catch blocks do not trap segmentation faults or other C++ signals (not to be confused with Qt "signals"). In order to trap a C++ segmentation fault signal, you need to install a signal handler for SIGSEGV.

However, once your program's memory get corrupted by something like a segmentation fault, it is not a good idea to simply trap it and go on running as if nothing has happened. It is far better to 1) find and fix these errors in the debugger instead of pretending they don't exist, and 2) if you do trap them with a signal handler, then the best thing to do is to tell the user that it happened and exit quickly. It really isn't safe to do anything else, because you don't know what damage the SIGSEGV has caused.