我正在编写一个加载输入的程序,直到键入一个特定的单词,在这种情况下它的单词“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;
}
}
}
我发现很多话题都在讨论同样的问题,但无论如何我都无法找到解决方案。谢谢你的回答。
答案 0 :(得分:3)
问题是您没有在重新分配时添加空终止符:
word = realloc(word, length + 1);
word[length - 1] = c;
此时,word
字符串未终止,因此strcmp
可能会在搜索空终止符时结束。"ko"
。例如,当您键入strcmp
时,word[2]
将确定字符0和1是相同的,并尝试检查word[length] = '\0';
- 您的程序未设置的位置。
添加此行以解决问题:
free
当与word
的比较失败时,您还应该将代码添加到konec
realloc
。
注意:您未正确使用word
:您应该将其分配回temp
,而不是将其分配回NULL
,并检查realloc
。否则,当 $tapplicant = $this->Tapplicant->find(
'all',
array(
'fields' => array(
'Tapplicant.*',
'Toutcome.*'
),
'order' => array('Tapplicant.AppDate' => 'DESC'),
'joins' => array(
array(
'table' => 'toutcome',
'alias' => 'Toutcome',
'type' => 'INNER',
'conditions' => array('Tapplicant.AppID = Toutcome.AppID' )
)
),
'limit' => 15
)
);
失败时,您将无法释放先前分配的单词。