336
votes

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

29
you can use inline assembly to attempt to execute privleged instructions: asm { cli; };Nate Koppenhaver
@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)Andrew Barber
any comment of throwing exception while one already propogates?? plz chk my answer below anc commentAbhinav
Redis uses the following *((char*)-1) = 'x'; code to induce a crash in order to debug read more in my answer hereShafik Yaghmour
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!Cory Trese

29 Answers

277
votes

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

117
votes

Try:

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

Found in:

#include <signal.h>
75
votes

Dividing by zero will crash the application:

int main()
{
    return 1 / 0;
}
65
votes
*((unsigned int*)0) = 0xDEAD;
52
votes

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

36
votes
 throw 42;

Just the answer... :)

17
votes

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.

11
votes

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.

9
votes

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.

9
votes

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
}
9
votes

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

7
votes
*( ( char* ) NULL ) = 0;

This will produce a segmentation fault.

7
votes

This one is missing:

int main = 42;
6
votes

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 :)

5
votes

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
votes

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();
}
3
votes
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.

3
votes
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.

3
votes

This is the snippet provided by Google in Breakpad.

  volatile int* a = reinterpret_cast<volatile int*>(NULL);
  *a = 1;
2
votes
int main(int argc, char *argv[])
{
    char *buf=NULL;buf[0]=0;
    return 0;
}
2
votes

Although this question already has an accepted answer...

void main(){
    throw 1;
}

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

2
votes

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
votes

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)

0
votes
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.

0
votes
int main()
{
    int *p=3;
    int s;
    while(1) {
        s=*p;
        p++;
    }
}
0
votes

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)

0
votes

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.

0
votes

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.

-2
votes
char*freeThis;
free(freeThis);

Freeing an uninitialized pointer is undefined behavior. On many platforms/compilers, freeThis will have a random value (whatever was at that memory location before). Freeing it will ask the system to free the memory at that address, which will usually cause a segmentation fault and make the program crash.