空指针操作在linux和windows下的区别

xiaoxiao2021-02-28  107

空指针的非法访问: * 在windows下可以用try-catch捕获住. * 在linux下, 无法用try-catch捕获住, 直接段错误, 程序崩溃了. 为了安全操作指针, 在使用指针前, 必须对指针进行非空检查。

实验

for (int i = 0; i < 10; i++) { printf("testcase_try_catch : i = %d\n", i); testcase_try_catch(argc, argv); } int testcase_try_catch(int argc, char* argv[]) { char* pBuf = new char[0x100]; try { if (NULL != pBuf) { memset(pBuf, 0, 0x100); strcpy(pBuf, "xello"); if (0 == (rand() % 2)) { delete []pBuf; pBuf = NULL; } // 如果不在使用指针前, 检查指针是否为空 // 当指针为空时进行赋值的后果 // windows : 会被try-catch捕获住 // linux : try-catch无法捕获, 直接段错误, 程序崩掉了 // 总结 : 为了安全的使用指针,在使用指针前,都要进行指针的有效性检查 // 不能依赖try-catch来预防指针为空的非法访问 // try-catch捕获的是异常(设计出来的改变流程的手段) // try-catch不可用来捕获非法访问(程序的错误) // 为了程序的兼容性, 空指针的检查时必须的 // if (NULL != pBuf) { *pBuf = 'h'; printf("%s\n", pBuf); // } } } catch (exception e) { printf("catch (exception e) : %s\n", e.what()); } catch (...) { // catch... 在linux下也捕获不了空指针非法访问 printf("catch (...)\n"); } if (NULL != pBuf) { delete []pBuf; } return 0; } run result testcase_try_catch : i = 0 hello testcase_try_catch : i = 1 ./Makefile: line 42: 4081 Segmentation fault ./testcase root@debian:/home/dev/testdir#
转载请注明原文地址: https://www.6miu.com/read-29619.html

最新回复(0)