我试图使一个Python程序接口与不同的崩溃进程(这是我的手)。不幸的是,我正在使用的程序甚至不会可靠地崩溃!所以我想做一个快速的c++程序,它会故意崩溃,但我不知道最好和最短的方法来做到这一点,有人知道在我的
int main() {
crashyCodeGoesHere();
}
使我的c++程序可靠地崩溃
我试图使一个Python程序接口与不同的崩溃进程(这是我的手)。不幸的是,我正在使用的程序甚至不会可靠地崩溃!所以我想做一个快速的c++程序,它会故意崩溃,但我不知道最好和最短的方法来做到这一点,有人知道在我的
int main() {
crashyCodeGoesHere();
}
使我的c++程序可靠地崩溃
当前回答
#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;
}
其他回答
abort()函数可能是最好的选择。它是C标准库的一部分,被定义为“导致异常程序终止”(例如,致命错误或崩溃)。
这是Breakpad中谷歌提供的代码片段。
volatile int* a = reinterpret_cast<volatile int*>(NULL);
*a = 1;
这是上面回答中给出的一个更有保证的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();
}
虽然这个问题已经有了公认的答案……
void main(){
throw 1;
}
还是……无效main(){throw 1;}
写入只读内存会导致分割错误,除非你的系统不支持只读内存块。
int main() {
(int&)main = 0;
}
我在Windows 7上用MingGW 5.3.0测试了它,在Linux Mint上用GCC测试了它。我认为其他编译器和系统也会有类似的效果。