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

偶尔善良 提交于 2019-12-28 01:39:39

问题


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


回答1:


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




回答2:


Try:

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

Found in:

#include <signal.h>



回答3:


Dividing by zero will crash the application:

int main()
{
    return 1 / 0;
}



回答4:


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



回答5:


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




回答6:


 throw 42;

Just the answer... :)




回答7:


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.




回答8:


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:


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.




回答10:


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
}



回答11:


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




回答12:


*( ( char* ) NULL ) = 0;

This will produce a segmentation fault.




回答13:


This one is missing:

int main = 42;



回答14:


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




回答15:


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




回答16:


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.




回答17:


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



回答18:


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.




回答19:


This is the snippet provided by Google in Breakpad.

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



回答20:


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



回答21:


Although this question already has an accepted answer...

void main(){
    throw 1;
}

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




回答22:


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.




回答23:


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)




回答24:


One that has not been mentioned yet:

((void(*)())0)();

This will treat the null pointer as a function pointer and then call it. Just like most methods, this is not guaranteed to crash the program, but the chances of the OS allowing this to go unchecked and of the program ever returning are negligible.




回答25:


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.




回答26:


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



回答27:


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)




回答28:


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.




回答29:


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.



来源:https://stackoverflow.com/questions/8481783/what-is-the-easiest-way-to-make-a-c-program-crash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!