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

int main() {
    crashyCodeGoesHere();
}

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


当前回答

答案是平台特定的,取决于你的目标。但这里是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
}

其他回答

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

}

希望它崩溃。欢呼。

我看到这里张贴了许多答案,它们将成为完成工作的幸运案例,但没有一个是100%确定崩溃的。一些会在一个硬件和操作系统上崩溃,另一些不会。 然而,根据官方c++标准,有一种标准方法可以使它崩溃。

引用c++标准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) { } }

我写了一个小代码来演示这一点,可以在这里找到并在Ideone上试用。

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提到throw没有try块导致隐式调用abort:

如果当前没有处理异常,则执行 没有操作数的抛出表达式调用std::terminate()

其他包括: throw from析构函数:ISO/IEC 14882§15.2/3

int* p=0;
*p=0;

这也应该崩溃。在Windows上,它与AccessViolation一起崩溃,我猜它应该在所有操作系统上都是一样的。

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

Try:

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

中发现:

#include <signal.h>