为什么在将 calloc 与 unsigned int 一起使用时 coverity 会抱怨

Why does coverity complain when using calloc with unsigned int

我有以下内容:

static unsigned int *tick = NULL;
...
 if (tick == NULL)
     tick = calloc(MAX_PORT,sizeof(unsigned int));
...

其功能按预期工作,但 coverity 抱怨: 解析警告(PW.INCOMPATIBLE_ASSIGNMENT_OPERANDS) 1. incompatible_assignment_operands: "int"类型的值不能赋值给"unsigned int *"类型的实体 我不完全明白为什么

错误消息表明 Coverity 认为 calloc returns 一个 int, 如果您没有包含 stdlib.h(对于旧 C 中的 calloc)),这可能会发生。 但这在现代 C 中是不允许的(即,在 C99 及更高版本中不允许隐式声明)。

"... which functionally works as expected"

不,这段代码不能在任何版本的 C 上编译,无论是新的还是旧的。

在称为 C90 的旧 C 版本中,您可能会忘记包含 stdlib.h,然后编译器会将 calloc 视为返回 int 的函数,而不是 void*.这就是静态分析器的作用。但是代码甚至不应该编译,因为即使在 C90 编译器上它也会导致诊断 - 您不能将 int 分配给 unsigned int*。它从来都不是有效的 C.

在标准 C 中,代码甚至不会走那么远,因为编译器会告诉您它不知道标识符 calloc 是什么。

所有这些都表明您的编译器 1) 旧且 2) 不兼容。