有很多静态分析工具可以检查指针的误用,此外,大部分编译器都有选项来监测本章提到的很多问题。比如说,GCC编译器的-Wall
选项可以启用编译器警告。
下面说明本章的一些示例会产生什么样的警告,这里我们忘记在调用函数时写上括号了:
if(getSystemStatus == 0) {
结果会产生如下警告:
warning: the address of 'getSystemStatus' will never be NULL
下面是一个本质上完全一样的错误:
if(getSystemStatus) {
不过,警告信息会有所不同:
warning: the address of 'getSystemStatus' will always evaluate as 'true'
使用不兼容的指针类型也会产生警告:
int (*fptrCompute)(int,int);
int addNumbers(int n1, int n2, int n3) {
return n1+n2+n3;
}
...
fptrCompute = addNumbers;
下面是警告信息:
warning: assignment from incompatible pointer type
没有初始化指针通常也会出问题:
char *securityQuestion;
strcpy(securityQuestion,"Name of your home town");
产生的警告信息相当直白:
warning: 'securityQuestion' is used uninitialized in this function
还有很多静态分析工具可用,有的免费,有的收费,它们一般都会提供比编译器更强的诊断功能。因为太过复杂,超出了本教程的范围,这里就不再举例了。
评论前必须登录!
注册