c - 如何在编译时检测或防止未初始化的数组元素?

标签 c arrays static-analysis

下面的示例显示了使用未初始化数组元素的代码:

#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;
}

gccval 而不是为 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/

相关文章:

sql - 传递表格数据的二进制格式

java - 在 Java 中的 int 数组中使用单引号打印空间问题

php - 关于如何根据数据库表检查数组的建议

c# - 在源代码级别运行的 C# 静态源代码分析

c# - 是否有任何工具可以报告注释掉的 .NET 代码?

javascript - Flow.js 从节点模块推断返回类型

c - 我不明白 C 指针

c - 如何初始化一个无符号字符数组?

c++ - 二进制文件中的模式搜索

php - 在 CakePHP 中获取有限字段