序
空指针的非法访问: * 在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;
}
*pBuf =
'h';
printf(
"%s\n", pBuf);
}
}
catch (exception e) {
printf(
"catch (exception e) : %s\n", e.what());
}
catch (...) {
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