下面的示例显示了使用未初始化数组元素的代码:
#include <stdio.h>
int main(void)
{
char str[10]; /* elements not initialized */
int val; /* variable not initialized */
printf("%s\n", str); /* no warning */
printf("%d\n", val); /* warning */
return 0;
}
gcc
为 val
而不是为 str
生成警告:
$ gcc -Wall -c uninitialized.c
uninitialized.c:9:20: warning: variable 'val' is uninitialized when used here [-Wuninitialized]
printf("%d\n", val); /* warning */
^~~
uninitialized.c:6:12: note: initialize the variable 'val' to silence this warning
int val; /* variable not initialized */
^
= 0
1 warning generated.
编译器可能得出这样的结论:str
实际上是 初始化的,因为指针本身有一个值。只是它的元素没有初始化。所以编译器是对的。
另一方面,编译器明确决定不在此处插入任何元素初始化,因此它知道数组中未初始化的元素。那为什么它不警告呢?
是否有任何编译器设置或其他工具可以帮助在编译时检测到这一点?我对任何 C 编译器都感兴趣,而不仅仅是 gcc
。
最佳答案
我不认为 GCC 会发现这种未初始化的缓冲区问题。有一些静态分析工具会尝试更好地检测未初始化的变量。正在运行 split确实检测到有问题,尽管它不是最有用的消息:
$ splint quick.c
Splint 3.1.2 --- 03 May 2009
quick.c: (in function main)
quick.c:8:20: Passed storage str not completely defined (*str is undefined):
printf (..., str, ...)
Storage derivable from a parameter, return value or global is not defined.
Use /*@out@*/ to denote passed or returned storage which need not be defined.
(Use -compdef to inhibit warning)
quick.c:9:20: Variable val used before definition
An rvalue is used that may not be initialized to a value on some execution
path. (Use -usedef to inhibit warning)
Finished checking --- 2 code warnings
关于c - 如何在编译时检测或防止未初始化的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34002295/