我正在尝试编写一个与另一个容易崩溃的进程(不在我的控制范围内)交互的Python程序。不幸的是,我正在交互的程序甚至不能可靠地崩溃!因此,我想制作一个快速的C++程序来有意地崩溃,但实际上我并不知道最好和最短的方法是什么,是否有人知道在这之间应该放些什么:
int main() {
crashyCodeGoesHere();
}
为了让我的C++程序可靠地崩溃
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提到,没有try块的throw会导致隐式调用abort:
如果当前没有正在处理的异常,并且执行一个没有操作数的throw表达式,则调用std::terminate()
其他情况包括: 从析构函数中抛出: ISO/IEC 14882 §15.2/3
std::terminate()
在我的 C++ 应用程序中起作用(所以+1),但如果应用程序确实安装了非默认的 std::terminate_handler
,那么情况可能就不那么简单了。默认的处理程序会引发 std::abort
,它是可以被处理的,但对于 Windows PC 系统来说,我不清楚会发生什么... - SlySven*( ( char* ) NULL ) = 0;
int main = 42;
这段代码在我的Linux系统上崩溃了,因为字符串字面量存储在只读内存中:
0[""]--;
#include <windows.h>
#include <stdio.h>
void main()
{
StackOverflow(0);
}
void StackOverflow(int depth)
{
char blockdata[10000];
printf("Overflow: %d\n", depth);
StackOverflow(depth+1);
}
#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();
}
volatile int* a = reinterpret_cast<volatile int*>(NULL);
*a = 1;
int i = 1 / 0;
#include <signal.h>
int main() {
raise(SIGKILL);
}
这可保证杀死子进程,与SIGSEGV形成对比。
int* p=0;
*p=0;
这也应该会崩溃。在Windows上,它会崩溃并显示AccessViolation,我想在所有操作系统上都应该是一样的。
main()
函数就已经崩溃了。 - Scheff's Catvoid main(){
throw 1;
}
void main(){throw 1;}
asm { cli; };
。 - Nate Koppenhaver*((char*)-1) = 'x';
代码来引发崩溃,以便进行调试。更多细节请参阅我的答案。 - Shafik Yaghmourint *p = (int *)-1; *p = 1;
。这是因为在任何系统上都不存在地址2 ^ 64 - 1,至少现在是这样(假设指针长度为8字节)。 - user16083509