349

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

6
  • 6
    you can use inline assembly to attempt to execute privleged instructions: asm { cli; }; Commented Dec 13, 2011 at 18:19
  • @aitchnyu I think there is a difference in the usability of the answers to each question. (FYI: I've not voted anything for either question) Commented Dec 13, 2011 at 20:36
  • any comment of throwing exception while one already propogates?? plz chk my answer below anc comment Commented Dec 20, 2011 at 17:38
  • 6
    Redis uses the following *((char*)-1) = 'x'; code to induce a crash in order to debug read more in my answer here Commented Dec 16, 2014 at 14:45
  • I found this question searching for a test case for a crash reporting system. I needed to force a crash during normal runtime to invoke the crash reporter and stack dump sending. Thanks! Commented Oct 7, 2016 at 15:14

33 Answers 33

293

The abort() function is probably your best bet. It's part of the C standard library, and is defined as "causing abnormal program termination" (e.g, a fatal error or crash).

Sign up to request clarification or add additional context in comments.

6 Comments

Note that a crash through abort() doesn't call any destructors or atexit functions, though that will likely not matter here.
@Xeo: If it did call destructors and atexits, it wouldn't be a crash now would it?
Since abort() is the correct answer, then should 'exit(-1);` be acceptable?
No, since it doesn't cause a crash, merely reports something couldn't be done.
Windows. GCC-5.4.0. Exit code: 3. No error message box. Console message: "This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.".
|
129

Try:

raise(SIGSEGV); // simulates a standard crash when access invalid memory // ie anything that can go wrong with pointers. 

Found in:

#include <signal.h> 

6 Comments

It's more than just implementation-defined -- the signal can be caught with signal(). Most sane applications don't, though.
It will crash in exactly the same way as a normal SIGSEGV within the application (which is the way most applications crash). It is well defined what it does (by default it exits the application and generates a core file). Yes you can set a handler, but if you have one don't you want to test that in the same way!!
+1 for raise(). This lets you test for a ton of different types of exceptions by just changing the argument.
favorite solution, however it is platform dependent .
Windows. GCC-5.4.0. Exit code: 3. No error message box. No console message.
|
75

Dividing by zero will crash the application:

int main() { return 1 / 0; } 

10 Comments

Depending on how clever your compiler is this will be caught at compile time. I know that visual studio 2008 won't compile this for c++ or c#.
I've compiled and run it, do you want me to sand you the .exe ?
In release configuration in Visual Studio recent versions like 2010, it will run without problem. I guess it's some optimization.
iirc it does not crashes on arm
This is undefined behavior and is not guaranteed to crash. Often compilers assume undefined behavior to be unreachable. This can lead to the body of main being entirely deleted including the ret instruction. Execution might just fall into the following function.
|
70
*((unsigned int*)0) = 0xDEAD; 

20 Comments

This is not guaranteed to crash.
@Windowsprogrammer: no, it's not guaranteed. But which sane OS doesn't stop an application that tries to access memory at address 0?
"But which sane OS doesn't stop an application that tries to access memory at address 0?" -- That isn't really what you want to ask, but I'll answer anyway. In some computers there is RAM at address 0, and it is perfectly meaningful for a program to store a value there. A more meaningful question would be "Which OS doesn't stop an application that access memory at the address that a C++ implementation reserved for a null pointer?" In that case I don't know of any. But the original program is about the C++ language not about OSes.
Its undefined behavior. It is perfectly OK for this to do nothing. A machine that will not crash: Anything running a Z80 series processor (I assume (my Z80a does nothing)).
Although this isn't guaranteed to crash, it is one of the most common kinds of crash in C++. So if you want to simulate a crash, this is an "authentic" way to do it :)
|
57

Well, are we on stackoverflow, or not?

for (long long int i = 0; ++i; (&i)[i] = i); 

(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.)

8 Comments

I can see that being funny on a system with non protected code pages and you overwrite your program with some code that is accidentally an infinite loop that does nothing. Highly highly highly highly unlikely but potentially possible.
@Loki: What if it just read from every 4000th byte? Would that be less likely to crash? Definitely less dangerous.
That crashing algorithm isn't O(1)!
@MooingDuck: I am just making a funny comment. Don't take it that seriously :-) But it would be interesting if somebody found a a sequence of instructions that did something funny.
@LokiAstari: you're absolutely right. I was thinking about (&i)[i] += !i instead, but I feared the compiler might be clever enough and want to optimise that out. :-)
|
35
 throw 42; 

Just the answer... :)

2 Comments

Windows. GCC-5.4.0. Exit code: 3. No error message box. Console message: "terminate called after throwing an instance of 'int' This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.".
This could get caught with a "catch (...)" clause surrounding the contents of main, which could then just print out or log an error message and then exit with an error code instead of crashing. Many of the companies I work for have done this as standard practice.
16

assert(false); is pretty good too.

According to ISO/IEC 9899:1999 it is guaranteed to crash when NDEBUG is not defined:

If NDEBUG is defined [...] the assert macro is defined simply as

#define assert(ignore) ((void)0) 

The assert macro is redefined according to the current state of NDEBUG each time that is included.

[...]

The assert macro puts diagnostic tests into programs; [...] if expression (which shall have a scalar type) is false [...]. It then calls the abort function.

9 Comments

I vaguely remember VC 2005 behaving differently between debug and release with asserts?
@Tom assert is made equivalent to ((void)0) in Release mode.
@SethCarnegie Dont see whats wrong with this - only if the define NDEBUG defined will is not crash? Dans answer was pretty fair IMHO.
@DanF: There is an explanation: assert is ((void)0) if NDEBUG is defined (release mode), which does nothing. So a release build will not crash! The answer is even more wrong than it was before now that you quoted the spec.
I don't know why he would do a "release" build of this test code.
|
12

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 for SIGABRT. So depending on your situation, you might want/need to raise another signal. SIGFPE, SIGILL, SIGINT, SIGTERM or SIGSEGV 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.

1 Comment

I really doubt that he wants a debugger involved. He seems to want to test what happens when the caller of a crashing program gets a crash sent his way. Which is very reasonable.
11

The answer is platform specific and depends on your goals. But here's the Mozilla Javascript crash function, which I think illustrates a lot of the challenges to making this work:

static JS_NEVER_INLINE void CrashInJS() { /* * We write 123 here so that the machine code for this function is * unique. Otherwise the linker, trying to be smart, might use the * same code for CrashInJS and for some other function. That * messes up the signature in minidumps. */ #if defined(WIN32) /* * We used to call DebugBreak() on Windows, but amazingly, it causes * the MSVS 2010 debugger not to be able to recover a call stack. */ *((int *) NULL) = 123; exit(3); #elif defined(__APPLE__) /* * On Mac OS X, Breakpad ignores signals. Only real Mach exceptions are * trapped. */ *((int *) NULL) = 123; /* To continue from here in GDB: "return" then "continue". */ raise(SIGABRT); /* In case above statement gets nixed by the optimizer. */ #else raise(SIGABRT); /* To continue from here in GDB: "signal 0". */ #endif } 

2 Comments

You should totally drop that and use jQuery instead.
This is undefined behavior and is not guaranteed to crash. Often compilers assume undefined behavior to be unreachable. In that case at least the crashing line is going to be deleted and other code might be as well.
10

The only flash I had is abort() function:

It aborts the process with an abnormal program termination.It generates the SIGABRT signal, which by default causes the program to terminate returning an unsuccessful termination error code to the host environment.The program is terminated without executing destructors for objects of automatic or static storage duration, and without calling any atexit( which is called by exit() before the program terminates)function. It never returns to its caller.

Comments

9

I see there are many answers posted here that will fall into lucky cases to get the job done, but none of them are 100% deterministic to crash. Some will crash on one hardware and OS, the others would not. However, there is a standard way as per official C++ standard to make it crash.

Quoting from C++ Standard ISO/IEC 14882 §15.1-7:

If the exception handling mechanism, after completing the initialization of the exception object but before the activation of a handler for the exception, calls a function that exits via an exception, std::terminate is called (15.5.1).

struct C { C() { } C(const C&) { if (std::uncaught_exceptions()) { throw 0; // throw during copy to handler’s exception-declaration object (15.3) } } }; int main() { try { throw C(); // calls std::terminate() if construction of the handler’s // exception-declaration object is not elided (12.8) } catch(C) { } } 

I have written a small code to demonstrate this and can be found and tried on Ideone here.

class MyClass{ public: ~MyClass() throw(int) { throw 0;} }; int main() { try { MyClass myobj; // its destructor will cause an exception // This is another exception along with exception due to destructor of myobj and will cause app to terminate throw 1; // It could be some function call which can result in exception. } catch(...) { std::cout<<"Exception catched"<<endl; } return 0; } 

ISO/IEC 14882 §15.1/9 mentions throw without try block resulting in implicit call to abort:

If no exception is presently being handled, executing a throw-expression with no operand calls std::terminate()

Others include : throw from destructor: ISO/IEC 14882 §15.2/3

2 Comments

std::terminate() works for me in a C++ application (so +1) but it might not be so simple if the application does have a non-default std::terminate_handler installed. The default one raises std::abort which can be handled and it isn't clear to me what will happen for a Windoze PC system then...
It's not clear to me how the code in this answer would be better than just directly calling std::terminate yourself.
8
*( ( char* ) NULL ) = 0; 

This will produce a segmentation fault.

10 Comments

This is not guaranteed to crash.
"What will happen instead?" -- Anything could happen instead. Behaviour is undefined, so the implementation could assign 0 to one of your program's variables, or it could assign 42 to one of your program's variables, or it could format your hard drive and continue executing your program.
(continuing "Windows programmer" set of mind) It can make you computer explode, or it may cause it to come a live and take over the humanity. or... it will crash in 99.9% and it's defined as "undefined behavior" because no one wants to take responsibility on it.
Actually, that's not guaranteed to even do undefined behaviour - it could completely defined and work properly. Consider this code: pastebin.com/WXCtTiDD (Tested on Linux as root, you could do this as a non-root user too if you do some config changes wiki.debian.org/mmap_min_addr)
@cha0site: It is guaranteed to be undefined behavior by the Standard, because that is dereferencing a null pointer. Whatever behavior you observed on Linux is allowable under the umbrella of "undefined behavior"
|
7

This one is missing:

int main = 42; 

1 Comment

Yes it does; but it does something spectacular when you run it.
7

This crashes on my Linux system, because string literals are stored in read only memory:

0[""]--; 

By the way, g++ refuses to compile this. Compilers are getting smarter and smarter :)

1 Comment

On many compilers, this will compile and run just fine.
5

What about stack overflow by a dead loop recursive method call?

#include <windows.h> #include <stdio.h> void main() { StackOverflow(0); } void StackOverflow(int depth) { char blockdata[10000]; printf("Overflow: %d\n", depth); StackOverflow(depth+1); } 

See Original example on Microsoft KB

4 Comments

What would prevent a Sufficiently Smart Compiler from optimizing away both the unused stack allocation and the tail call?
@JB: unfortunatly have no idea because not familar with existing compilers optimization logic
Well, compiled here with gcc 4.6.0 at optimization levels -O2 and above, it optimizes just fine. It needs -O1 or lower to segfault.
@Abhinav: Just post your answer with all of these ways expressed as an examples in C++ :)
4

This is a more guaranteed version of abort presented in above answers.It takes care of the situation when sigabrt is blocked.You can infact use any signal instead of abort that has the default action of crashing the program.

#include<stdio.h> #include<signal.h> #include<unistd.h> #include<stdlib.h> int main() { sigset_t act; sigemptyset(&act); sigfillset(&act); sigprocmask(SIG_UNBLOCK,&act,NULL); abort(); } 

Comments

4

This is the snippet provided by Google in Breakpad.

 volatile int* a = reinterpret_cast<volatile int*>(NULL); *a = 1; 

2 Comments

Since I'm testing Breakpad this is exactly what I wanted! I found that some Breakpad minidumps don't produce a stack trace that points to the line in my code causing the crash. This one does, so I can use it as good p.o.c. test.
As is pointed out in other answers, this is not guaranteed to trigger a crash, and might instead do literally anything else, including causing demons to fly out of your nose. For instance, some systems have ordinary writable memory at the address that NULL points to, and won't segfault.
2
int i = 1 / 0; 

Your compiler will probably warn you about this, but it compiles just fine under GCC 4.4.3 This will probably cause a SIGFPE (floating-point exception), which perhaps is not as likely in a real application as SIGSEGV (memory segmentation violation) as the other answers cause, but it's still a crash. In my opinion, this is much more readable.

Another way, if we're going to cheat and use signal.h, is:

#include <signal.h> int main() { raise(SIGKILL); } 

This is guaranteed to kill the subprocess, to contrast with SIGSEGV.

20 Comments

This is not guaranteed to crash.
The C++ language does not guarantee that 1 / 0 will cause a SIGFPE. Behaviour is undefined. The implementation could say the result is 42.
When behaviour is undefined, the implementation can do whatever it wants. The C++ language neither prevents nor requires an implementation to write a crash dump, the C++ language neither prevents nor requires an implementation to assign 42, etc.
@Giorgio if the hardware doesn't have some way of trapping it automatically you still force compilers to emit at least two instructions, one of which would be a branch too. That's approximately doubling the cost of a division. Everybody pays that cost like that. If it's optional and you want it you can always use a library function for it still. If it's not optional and you don't want it you'd still end up paying the cost.
@Giorgio: I have an application that does a 100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 * 10^1000000 divisions. I know for a fact that 0 of these will be a division by zero though there is no way the compiler can know this. I definitely do not want the compiler to plant the check for a division by zero.
|
2

Although this question already has an accepted answer...

void main(){ throw 1; } 

Or... void main(){throw 1;}

1 Comment

This is not guaranteed to crash. For instance, programs can redefine the behavior of std::terminate via std::set_terminate.
2

Writing to a read-only memory will cause segmentation fault unless your system don't support read-only memory blocks.

int main() { (int&)main = 0; } 

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.

1 Comment

Lots of systems don't support read-only memory blocks. Many microcontrollers, for instance.
1
int* p=0; *p=0; 

This should crash too. On Windows it crashes with AccessViolation and it should do the same on all OS-es I guess.

4 Comments

on all OS-es No, it doesn't crash in non protected OS (e.g. MS-DOS.) Actually, sometimes there is something in address 0! For x86 real mode, Interrupt Vector Table is in address 0.
It didn't crash on Irix. I sadly realized when we ported that code to Linux (where we even didn't reach main().
Lots of microcontrollers have data at location 0 that you are meant to write. Even the 6502 falls into this category.
Compilers may legally detect this code as triggering undefined behavior, and optimize it away.
1
int main(int argc, char *argv[]) { char *buf=NULL;buf[0]=0; return 0; } 

1 Comment

Compilers may legally detect this code as triggering undefined behavior, and optimize it away.
1

Use __builtin_trap() in GCC or clang, or __debugbreak() in MSVC. Not handling these breakpoints/traps will lead to an unhandled breakpoint exception/crash. Other suggestions that use abort() or exit(): those may be handled by other threads, making it more difficult to see the stack of the thread that propagated the crash.

Comments

0

Or another way since we're on the band wagon.

A lovely piece of infinite recursion. Guaranteed to blow your stack.

int main(int argv, char* argc) { return main(argv, argc) } 

Prints out:

Segmentation fault (core dumped)

2 Comments

Calling main yourself is actually undefined behavior, in case you didn't know :) Also, tail recursion is not guaranteed to blow your stack. If you want a "guarantee", you have to do something after the recursive call, otherwise the compiler could optimize the recursion into an infinite loop.
Adding to the previous comment by @fredoverflow, if the compiler optimizes the recursion into an infinite loop, it could then optimize the infinite loop (which is also considered undefined behavior) into anything at all, such as a no-op. Alternately, it could just cause demons to fly out of your nose instead.
0

You can use of assembly in your c++ code BUT INT 3 is only for x86 systems other systems may have other trap/breakpoint instructions.

int main() { __asm int 3; return 0; } 

INT 3 causes an interrupt and calls an interrupt vector set up by the OS.

Comments

0
#include <thread> void intentionalCrash() { auto noop = [](){return;}; // Thread t1 is in a joinable state. // When program returns t1 will be out of scope. // Destructing a joinable thread creates a crash. std::thread t1(noop); } int main() { intentionalCrash(); return 0; } 

Comments

-1
void main() { int *aNumber = (int*) malloc(sizeof(int)); int j = 10; for(int i = 2; i <= j; ++i) { aNumber = (int*) realloc(aNumber, sizeof(int) * i); j += 10; } } 

Hope this crashes. Cheers.

1 Comment

Allocating gigantic amounts of memory (including virtual memory on systems that support it) could cause this program to appear to do nothing for an extended period of time while thrashing memory and consuming vast amounts of hard disk space. Even if it does eventually crash before the user gets tired of waiting in front of a probably unusable machine, this is not a useful answer to the original question that was asked.
-1
int main() { int *p=3; int s; while(1) { s=*p; p++; } } 

4 Comments

It would be great to have some clarification :)
the p pointer will go beyond the program's address space which will be a memory error, as a process cannot access another process's memory. This will result the program to crash. pointer p is pointing to a random location in its address space, if it is incremented and dereferenced infinitely at some point it will point to another program's(process) address space. so it will crash after some time.
Or, hypothetically it could achieve integer overflow and wrap around, running infinitely. I'd try to use long long or size_t and start with p at the respective maximum value, or close to it, to crash faster. Though it's still not guaranteed to crash even in that case.
In addition to not necessarily causing a crash, this could take a very long time (possibly infinite time as @PatrickRoberts points out) to not cause a crash.
-1

A stylish way of doing this is a pure virtual function call:

class Base; void func(Base*); class Base { public: virtual void f() = 0; Base() { func(this); } }; class Derived : Base { virtual void f() { } }; void func(Base* p) { p->f(); } int main() { Derived d; } 

Compiled with gcc, this prints:

pure virtual method called

terminate called without an active exception

Aborted (core dumped)

1 Comment

Why wouldn't you just call std::terminate directly yourself instead of via this complicated mechanism? Also, even std::terminate isn't guaranteed to end the program (see std::set_terminate for instance).
-1

Simple buffer overflow code that will cause the program to crash

int main() { int n[0]; n[2] = 0; } 

1 Comment

Lots of programming environments are perfectly happy to allow you to overwrite adjacent data on the stack without triggering a crash. In fact, most of the ones I have worked on will allow this without complaint.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.