I'm trying to make a Python program that interfaces with a different crashy process (that's out of my hands). Unfortunately the program I'm interfacing with doesn't even crash reliably! So I want to make a quick C++ program that crashes on purpose but I don't actually know the best and shortest way to do that, does anyone know what to put between my:
int main() {
crashyCodeGoesHere();
}
to make my C++ program crash reliably
Well, are we on stackoverflow, or not?
(Not guaranteed to crash by any standards, but neither are any of the suggested answers including the accepted one since
SIGABRT
could have been caught anyway. In practice, this will crash everywhere.)Writing to a read-only memory will cause segmentation fault unless your system don't support read-only memory blocks.
I have tested it with MingGW 5.3.0 on Windows 7 and GCC on Linux Mint. I suppose that other compilers and systems will give a similar effect.
Since a crash is a symptom of invoking undefined behaviour, and since invoking undefined behaviour can lead to anything, including a crash, I don't think you want to really crash your program, but just have it drop into a debugger. The most portable way to do so is probably
abort()
.While
raise(SIGABRT)
has the same effect, it is certainly more to write. Both ways however can be intercepted by installing a signal handler forSIGABRT
. So depending on your situation, you might want/need to raise another signal.SIGFPE
,SIGILL
,SIGINT
,SIGTERM
orSIGSEGV
might be the way to go, but they all can be intercepted.When you can be unportable, your choices might be even broader, like using
SIGBUS
on linux.This crashes on my Linux system, because string literals are stored in read only memory:
By the way, g++ refuses to compile this. Compilers are getting smarter and smarter :)
assert(false);
is pretty good too.According to ISO/IEC 9899:1999 it is guaranteed to crash when NDEBUG is not defined:
What about stack overflow by a dead loop recursive method call?
See Original example on Microsoft KB