Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code to crash intentionally [duplicate]

Possible Duplicate:
What is the easiest way to make a C++ program crash?

There's a construct I see frequently in our codebase, where the program gets into an invalid state somehow, the code will do something intentionally wrong, just to force a crash. It usually goes something like this:

if(<something is wrong>)
{
    int *ptr = NULL;
    *ptr = 0;
}

This of course causes a null reference exception and crashes the program in an unrecoverable manner. I'm just wondering if this is really the best way to do this? First of all, it doesn't read well. Without a comment, you might not realize that the crash that occurs here is intended. Secondly, there's pretty much no way to recover from this. It doesn't throw an exception, so it can't be handled by other code. It just kills the program dead with no way of backtracking. It also doesn't give much of a clue as to why it had to crash here. And it will crash in all builds, unlike, say, an assert. (We do have a pretty robust assert system available, but it isn't always used in cases like this.)

It's the style we're using all over the place, and I'm in no position to try and convince anyone otherwise. I'm just curious how common this is in the industry.

like image 401
Darrel Hoffman Avatar asked Nov 21 '12 21:11

Darrel Hoffman


2 Answers

You can't "crash" a program in a deliberate way, because by its very definition a crash is when a program goes wrong and fails to behave deterministically.

The standard way to terminate execution is via std::terminate; the usual way to achieve this is to call std::abort, which raises an unblockable signal against the process (leading to std::terminate automatically) and also causing many operating systems to produce a core dump.

like image 106
Kerrek SB Avatar answered Sep 20 '22 07:09

Kerrek SB


You should throw an exception, which is basically causing a crash deliberately and in a controlled manner. Here is an example with help from this question.

throw string("something_went_wrong");

Better yet is that the error is caught or fixed. Assert would also be a fine choice.

like image 31
PearsonArtPhoto Avatar answered Sep 21 '22 07:09

PearsonArtPhoto