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

int main() {
    crashyCodeGoesHere();
}

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


当前回答

Try:

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

中发现:

#include <signal.h>

其他回答

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

}

希望它崩溃。欢呼。

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

Try:

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

中发现:

#include <signal.h>
#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;
}

断言(假);也很不错。

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

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