1、空指针问题
try
{
char* p = new char[256];
strcpy(p, "hello");
int size = strlen(p);
printf("strlen = %d\n", size);
delete[] p;
p = nullptr;
strcpy(p, "world");
size = strlen(p);
printf("strlen = %d\n", size);
}
catch (const std::exception& e)
{
printf("err:%s\n", e.what());
}
//catch (...)
//{
// DWORD errcode = GetLastError();
// printf("Unknown err, code = %d\n", errcode);
//}
上面代码中如果去掉p=nullptr那么p就变为了野指针,程序可能不会出错,但是会产生巨大的隐藏风险:p指针已经被delete,所指向的内存已被操作系统回收,strcpy拷贝的数据随时可能被后续的其他数据所覆盖;
2、除0操作产生0xc0000094异常代码:被除数不能为零
try
{
int x = 10;
int y = 0;
int z = x / y;
}
catch (const std::exception& e)
{
printf("err:%s\n", e.what());
}
//catch (...)
//{
// DWORD errcode = GetLastError();
printf("Unknown err, code = %d\n", errcode);
//}
3、删除已经被删除的对象产生未经处理的异常: 0xC0000374: 堆已损坏
try
{
A* p = new A();
p->print();
p->a = 12;
p->print();
delete p;
p->a = 25;
p->print();
delete p;
}
catch (const std::exception& e)
{
printf("err:%s\n", e.what());
}
//catch (...)
//{
// DWORD errcode = GetLastError();
printf("Unknown err, code = %d\n", errcode);
//}