我试图使一个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 中止(核心转储)

其他回答

这会在我的Linux系统上崩溃,因为字符串文字存储在只读内存中:

0[""]--;

顺便说一下,g++拒绝编译这个。编译器变得越来越聪明:)

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

除以0会导致应用程序崩溃:

int main()
{
    return 1 / 0;
}

简单的缓冲区溢出代码,将导致程序崩溃

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

这是上面回答中给出的一个更有保证的abort版本。它负责处理sigabrt被阻塞时的情况。实际上,您可以使用任何信号来代替具有使程序崩溃的默认操作的abort。

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