未初始化的值是由堆栈分配创建的 - valgrind [英] Uninitialised value was created by a stack allocation - valgrind
问题描述
我使用 valgrind 通过选项 track-origins=yes
调试我的代码并遇到了这个错误.
I used valgrind to debug my code with the option track-origins=yes
and came across this error.
$ valgrind --track-origins=yes ./frgtnlng < in > out
==7098==
==7098== Conditional jump or move depends on uninitialised value(s)
==7098== at 0x4C2F1BC: strcmp (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==7098== by 0x400857: main (frgtnlng.c:24)
==7098== Uninitialised value was created by a stack allocation
==7098== at 0x40064C: main (frgtnlng.c:9)
==7098==
==7098== Conditional jump or move depends on uninitialised value(s)
==7098== at 0x40085A: main (frgtnlng.c:24)
==7098== Uninitialised value was created by a stack allocation
==7098== at 0x40064C: main (frgtnlng.c:9)
第 9 行是:
scanf("%d", &t);
我不明白这会如何导致问题.
I don't understand how this could cause the problem.
frgtnlng.c:
frgtnlng.c:
#include <stdio.h>
#include <string.h>
int main(void)
{
int t, n, k, l, i, j, z, out[100];
char f[5][100], m[5][50][50];
scanf("%d", &t);
while (t--) {
for (i = 0; i < 100; i++)
out[i] = 0;
scanf("%d%d", &n, &k);
for (i = 0; i < n; i++)
scanf("%s", f[i]);
for (i = 0; i < k; i++) {
scanf("%d", &l);
for (j = 0; j < l; j++)
scanf("%s", m[i][j]);
}
for (i = 0; i < k; i++)
for (j = 0; j < l; j++)
for (z = 0; z < n; z++) {
if (strcmp(m[i][j], f[z]) == 0)
out[z] = 1;
}
for (i = 0; i < n; i++) {
if (out[i])
printf("YES ");
else
printf("NO ");
}
printf("\n");
}
return 0;
}
在:
2
3 2
piygu ezyfo rzotm
1 piygu
6 tefwz tefwz piygu ezyfo tefwz piygu
4 1
kssdy tjzhy ljzym kegqz
4 kegqz kegqz kegqz vxvyj
推荐答案
valgrind 的行号关闭:它应该报告分配行号的 7,而不是 9.然而,错误行 24 是正确的 - 问题在这里:
valgrind's line number is off: it should have reported 7, not 9, for the allocation line number. The error line 24, however, is correct - the problem is here:
if (strcmp(m[i][j], f[z]) == 0)
问题是 j
从 0 到 l-1
循环,包括在内,但 l
是它在最后 读取二维数组的循环的迭代,即 4.这就是为什么每次遇到数组中少于 4 个条目的行时,它从数组的未初始化部分读取.
The issue is that j
loops from 0 to l-1
, inclusive, but l
is whatever it has been set to in the last iteration of the loop that reads the 2D array, i.e. 4. That's why each time it comes to a line in the array with fewer than 4 entries it reads from uninitialized portion of the array.
解决方法是通过将 l
设为数组 l[5]
并使用 l[i]
来分别存储各个行的长度在两个循环中:
The fix is to store lengths of individual rows separately by making l
an array l[5]
, and using l[i]
in both loops:
for (i = 0; i < k; i++) {
scanf("%d", &l[i]);
for (j = 0; j < l[i]; j++)
scanf("%s", m[i][j]);
}
for (i = 0; i < k; i++)
for (j = 0; j < l[i]; j++)
for (z = 0; z < n; z++) {
if (strcmp(m[i][j], f[z]) == 0)
out[z] = 1;
}
这篇关于未初始化的值是由堆栈分配创建的 - valgrind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!