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

int main() {
    crashyCodeGoesHere();
}

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


当前回答

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

其他回答

abort()函数可能是最好的选择。它是C标准库的一部分,被定义为“导致异常程序终止”(例如,致命错误或崩溃)。

断言(假);也很不错。

根据ISO/IEC 9899:1999,当没有定义NDEBUG时,保证会崩溃:

如果NDEBUG定义为[…]assert宏被简单地定义为 # assert(void)0) assert宏每次被包含时都会根据NDEBUG的当前状态重新定义。 […] assert宏将诊断测试放入程序中;[…if表达式(它应该有一个标量类型)为假[…]。它 然后调用中止函数。

答案是平台特定的,取决于你的目标。但这里是Mozilla Javascript崩溃函数,我认为这说明了很多挑战,使这个工作:

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
}

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

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 中止(核心转储)

由于崩溃是调用未定义行为的症状,并且由于调用未定义行为可能导致任何事情,包括崩溃,我认为您不希望真正使程序崩溃,而只是将它放入调试器中。最可移植的方法可能是abort()。

虽然raise(SIGABRT)具有相同的效果,但它肯定更适合编写。然而,这两种方式都可以通过为SIGABRT安装信号处理程序来拦截。因此,根据您的情况,您可能想要/需要发出另一个信号。SIGFPE, SIGILL, SIGINT, SIGTERM或SIGSEGV可能是可行的方法,但它们都可以被拦截。

当您无法移植时,您的选择可能更广泛,比如在linux上使用SIGBUS。