c++的atexit()函数奇怪的崩溃
Strange crash with C++ atexit() function
我使用MSVC与Visual Studio 2013。这是我正在编译的代码:
#include <iostream>
using namespace std;
void crash()
{
cout << "crash?" << endl;
system("PAUSE");
}
int main(int argc, char *argv[])
{
atexit(crash);
//while(true);
return 0;
}
现在的方式-它像一个魅力。我启动程序,它进入崩溃功能,暂停,我按下一个键,它正常关闭。所有的酷。但是,如果取消while循环的注释并使用控制台上的X按钮关闭它,endl函数内部就会崩溃。我能够确定崩溃是由_ostrs .拓宽()引起的。这是endl函数的实现,由MSVC提供:
template<class _Elem,
class _Traits> inline
basic_ostream<_Elem, _Traits>&
__CLRCALL_OR_CDECL endl(basic_ostream<_Elem, _Traits>& _Ostr)
{ // insert newline and flush stream
_Ostr.put(_Ostr.widen('n'));
_Ostr.flush();
return (_Ostr);
}
使用Ctrl+C终止程序会产生相同的效果。我该如何解决这个问题?
看来我的怀疑是真的。我这样修改代码:
#include <iostream>
using namespace std;
#include <Windows.h>
void crash()
{
printf("%in", GetCurrentThreadId());
system("PAUSE");
}
int main()
{
printf("%in", GetCurrentThreadId());
atexit(crash);
//while(true);
return 0;
}
当程序正常存在时,两个printf()s显示相同的线程id,但是当我按Ctrl+C或X按钮时,线程id不同,这解释了崩溃,并且当您考虑它时,它很有意义。因此,这里有一个如何解决这个问题的小示例:
#include <iostream>
#include <conio.h>
using namespace std;
#include <Windows.h>
volatile bool wantClose = false;
void OnExit()
{
cout << GetCurrentThreadId() << endl;
system("PAUSE");
}
BOOL WINAPI OnConsoleClose(DWORD dwCtrlType)
{
wantClose = true; // set a flag that the console wants us to close
ExitThread(0); // kill this thread immediately so it doesn't make the console stuck
return FALSE;
}
int main()
{
cout << GetCurrentThreadId() << endl;
SetConsoleCtrlHandler(OnConsoleClose, TRUE); // handle close requests from the console
atexit(OnExit);
while(!wantClose); // at some point in our code we will have to check whether the console wants us to close down
return 0;
}
请注意:使用system("PAUSE")和busy waiting只是为了使示例保持简单。我不建议在实际代码中使用。
相关文章:
- 内联映射初始化的动态atexit析构函数崩溃
- 执行函数时导致崩溃的变量
- C 回调函数在对象 pascal 上崩溃
- 除非使用某些寄存器,否则函数挂钩会崩溃
- Linux c++.在预加载的共享库中定义的基类的崩溃调用函数
- Rcpp 函数在打包时使 RStudio 崩溃
- 使用 MS 绕道挂钩在调用钩子函数时崩溃C++
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- 使用唯一指针调用函数会使我的程序崩溃
- 钩/绕道 d3d9 (现在/结束场景) - 似乎调用我的函数然后崩溃
- 程序在为链表创建推送函数时崩溃
- 递归导致程序崩溃,但 while 循环中的相同概念不是来自C++析构函数
- 从 C# 模块调用C++函数引发随机崩溃
- C++设置器函数崩溃
- EGL 在第一次 opengl 函数调用时崩溃
- 我需要做一个空函数循环回来,而不会让它崩溃或跳过
- 当我使用 ALSA lib 的函数"snd_pcm_readi"时它崩溃了
- 在C++中删除指针数组时析构函数崩溃
- 使用向量的函数崩溃,调试器说访问冲突读取位置
- 我的单例中的数组在离开函数后没有保留信息,然后在尝试再次访问信息时崩溃