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

C++Crash

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

Try:

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

Found in:

#include <signal.h>

Solution 3 - C++

Dividing by zero will crash the application:

int main()
{
    return 1 / 0;
}

Solution 4 - C++

*((unsigned int*)0) = 0xDEAD;

Solution 5 - C++

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

Solution 6 - C++

 throw 42;

Just the answer... :)

Solution 7 - C++

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.

Solution 8 - C++

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.

Solution 9 - C++

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
}

Solution 10 - C++

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.

Solution 11 - C++

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

Solution 12 - C++

*( ( char* ) NULL ) = 0;

This will produce a segmentation fault.

Solution 13 - C++

This one is missing:

int main = 42;

Solution 14 - C++

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

Solution 15 - C++

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

Solution 16 - C++

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

Solution 17 - C++

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.

Solution 18 - C++

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.

Solution 19 - C++

Although this question already has an accepted answer...

void main(){
    throw 1;
}

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

Solution 20 - C++

This is the snippet provided by Google in Breakpad.

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

Solution 21 - C++

int main(int argc, char *argv[])
{
    char *buf=NULL;buf[0]=0;
    return 0;
}

Solution 22 - C++

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.

Solution 23 - C++

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)

Solution 24 - C++

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.

Solution 25 - C++

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

Solution 26 - C++

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)

Solution 27 - C++

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.

Solution 28 - C++

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.

Solution 29 - C++

#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;
}

Solution 30 - C++

Simple buffer overflow code that will cause the program to crash

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

Solution 31 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjonathan topfView Question on Stackoverflow
Solution 1 - C++user149341View Answer on Stackoverflow
Solution 2 - C++Martin YorkView Answer on Stackoverflow
Solution 3 - C++Roee GavirelView Answer on Stackoverflow
Solution 4 - C++Keith NicholasView Answer on Stackoverflow
Solution 5 - C++sam hocevarView Answer on Stackoverflow
Solution 6 - C++MackeView Answer on Stackoverflow
Solution 7 - C++Dan FView Answer on Stackoverflow
Solution 8 - C++PlasmaHHView Answer on Stackoverflow
Solution 9 - C++Paul BiggarView Answer on Stackoverflow
Solution 10 - C++samridhiView Answer on Stackoverflow
Solution 11 - C++AbhinavView Answer on Stackoverflow
Solution 12 - C++wrrenView Answer on Stackoverflow
Solution 13 - C++mvdsView Answer on Stackoverflow
Solution 14 - C++fredoverflowView Answer on Stackoverflow
Solution 15 - C++sllView Answer on Stackoverflow
Solution 16 - C++bashrcView Answer on Stackoverflow
Solution 17 - C++user836352View Answer on Stackoverflow
Solution 18 - C++laci37View Answer on Stackoverflow
Solution 19 - C++noɥʇʎԀʎzɐɹƆView Answer on Stackoverflow
Solution 20 - C++Cory TreseView Answer on Stackoverflow
Solution 21 - C++Aniket IngeView Answer on Stackoverflow
Solution 22 - C++NO_NAMEView Answer on Stackoverflow
Solution 23 - C++hookenzView Answer on Stackoverflow
Solution 24 - C++senthilView Answer on Stackoverflow
Solution 25 - C++sc_csView Answer on Stackoverflow
Solution 26 - C++Martin BroadhurstView Answer on Stackoverflow
Solution 27 - C++BattleTested_закалённый в боюView Answer on Stackoverflow
Solution 28 - C++G HuxleyView Answer on Stackoverflow
Solution 29 - C++Kavit ShahView Answer on Stackoverflow
Solution 30 - C++Anic17View Answer on Stackoverflow
Solution 31 - C++Z RevView Answer on Stackoverflow