gpt4 book ai didi

c - valgrind错误条件跳转

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:22 25 4
gpt4 key购买 nike

我正在编写一个加载输入直到输入特定单词的程序,在本例中是单词“konec”。虽然我的程序似乎工作正常,但我无法解决这个 Valgrind 错误

==16573== Memcheck, a memory error detector   
==16573== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==16573== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==16573== Command: ./s_main_o
==16573==
==16573== Conditional jump or move depends on uninitialised value(s)
==16573== at 0x4C2A020: strcmp (mc_replace_strmem.c:711)
==16573== by 0x4008D7: main (main.c:41)
==16573== Uninitialised value was created by a heap allocation
==16573== at 0x4C28CCE: realloc (vg_replace_malloc.c:632)
==16573== by 0x40089C: main (main.c:38)
==16573==
==16573== Conditional jump or move depends on uninitialised value(s)
==16573== at 0x4C2A024: strcmp (mc_replace_strmem.c:711)
==16573== by 0x4008D7: main (main.c:41)
==16573== Uninitialised value was created by a heap allocation
==16573== at 0x4C28CCE: realloc (vg_replace_malloc.c:632)
==16573== by 0x40089C: main (main.c:38)
==16573==
==16573==
==16573== HEAP SUMMARY:
==16573== in use at exit: 0 bytes in 0 blocks
==16573== total heap usage: 8 allocs, 8 frees, 1,125 bytes allocated
==16573==
==16573== All heap blocks were freed -- no leaks are possible
==16573==
==16573== For counts of detected and suppressed errors, rerun with: -v
==16573== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 4 from 4)

这里是部分使用的代码

int main() {

int numberOfWords, i;
char** words;
char* word;
int* rarity;
char* konec = "konec";
int amount = 0;
double percentage;
words = malloc(10 * sizeof (char*));
rarity = calloc(256, sizeof (int));
numberOfWords = 0;
words[0] = 0;
int working = 1;

while (working == 1) {
int length = 0;
word = calloc((length + 1),sizeof (char));
char c;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\n') {
break;
}
length++;
word = realloc(word, length + 1);
word[length - 1] = c;
}
if (strcmp(word, konec) == 0) {
working = 0;
free(word);
break;
}
}
}

我发现很多主题都在讨论同一个问题,但我还是找不到解决方案。感谢您的回答。

最佳答案

问题是您没有在重新分配时添加空终止符:

word = realloc(word, length + 1);
word[length - 1] = c;

此时,word 字符串未终止,因此 strcmp 可能会在搜索空终止符时结束。例如,当您键入“ko”时,strcmp 将确定字符 0 和 1 相同,并尝试检查 word[2] - 您的程序未设置的位置。

添加这一行来解决问题:

word[length] = '\0';

当与 konec 比较不成功时,您还应该将代码添加到 free word

注意:您没有正确使用 realloc:您不应将其分配回 word,而应将其分配给 temp ,并检查它是否为 NULL。否则,当 realloc 失败时,您将无法释放先前分配的字。

关于c - valgrind错误条件跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30397477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com