【发布时间】:2017-10-03 11:44:22
【问题描述】:
我有一个程序在使用任何类型的优化(-O1、-O2、-O3)时触发-Wmaybe-uninitialized,以下是我可以制作的重现此行为的最小代码。
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
struct result {
int res;
};
struct graph {
int vertices[5];
};
// In reality this is a backtracking search.
void computational_search (struct graph *g, struct result *out) {
out->res = 0;
int i;
for (i=0; i<5; i++) {
out->res += g->vertices[i];
}
}
// In reality queries a database of geometrical graphs.
void next_graph (struct graph *g)
{
int i;
for (i=0; i<5; i++) {
g->vertices[i] += rand();
}
}
enum format_t {
FMT = 1,
FMT_1 = 2
};
int main()
{
int val = rand()%10;
int num_graphs = 5;
struct graph g;
struct result res;
uint64_t *count;
if (val & FMT) {
count = malloc(sizeof(uint64_t)*num_graphs);
}
int i;
for (i=0; i<num_graphs; i++) {
next_graph (&g);
computational_search (&g, &res);
if (val & FMT) {
count[i] = res.res; /* ERROR HERE */
}
}
return 0;
}
我知道有一个执行路径,其中count 未初始化,但它没有在那里使用。优化器可以做一些可能使用count uninitialized 的事情吗?
使用gcc -Wall -O1 test.c 编译在 gcc 5.4.0 上输出:
test.c: In function ‘main’:
test.c:43:15: warning: ‘count’ may be used uninitialized in this function [-Wmaybe-uninitialized]
uint64_t *count;
^
-O2 和 -O3 也是如此,但-O0 则不然。
【问题讨论】:
-
可以添加编译器输出吗?
-
你忘了告诉我们错误是什么以及在哪里。
-
在
gcc 5.4.0上无法重现 -
仅仅因为你可以看到
arr必须在使用前被初始化并不意味着编译器可以证明它。在一般情况下证明它是不可判定的。 -
因此您有一个未初始化且未使用的变量(在您的特定用例中)。似乎是一个很好的警告理由?这不是您编写稳定代码的方式。首先没有明显的理由使用 malloc。总是堆栈分配和初始化变量,问题解决了。奇怪的代码会出现奇怪的问题。
标签: c gcc gcc-warning