我试图使一个Python程序接口与不同的崩溃进程(这是我的手)。不幸的是,我正在使用的程序甚至不会可靠地崩溃!所以我想做一个快速的c++程序,它会故意崩溃,但我不知道最好和最短的方法来做到这一点,有人知道在我的

int main() {
    crashyCodeGoesHere();
}

使我的c++程序可靠地崩溃


当前回答

一种时髦的方法是使用纯虚函数调用:

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

用gcc编译,输出:

纯虚方法调用 在没有活动异常时调用Terminate 中止(核心转储)

其他回答

*((unsigned int*)0) = 0xDEAD;
#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;
}
int i = 1 / 0;

您的编译器可能会警告您这一点,但在GCC 4.4.3下它编译得很好 这可能会导致SIGFPE(浮点异常),这在实际应用程序中可能不像SIGSEGV(内存分段违反)那样可能导致其他答案,但它仍然是崩溃。在我看来,这样可读性更强。

另一种方法,如果我们要欺骗和使用signal.h,是:

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

这保证杀死子进程,与SIGSEGV形成对比。

我们到底是不是在stackoverflow上?

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

(根据任何标准都不保证会崩溃,但也没有任何建议的答案,包括被接受的答案,因为SIGABRT无论如何都可能被捕获。实际上,这会在任何地方崩溃。)

Try:

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

中发现:

#include <signal.h>