[英]Invalid read of size 1 when using valgrind
使用valgrind時,我得到以下輸出:
==19923== Invalid read of size 1
==19923== at 0x52CCCC0: vfprintf (vfprintf.c:1632)
==19923== by 0x52F4772: vasprintf (vasprintf.c:59)
==19923== by 0x52D3A56: asprintf (asprintf.c:35)
==19923== by 0x400D77: addToList (pa1.c:124)
==19923== by 0x4010AF: md5Hash (pa1.c:220)
==19923== by 0x401138: newFile (pa1.c:244)
==19923== by 0x401260: searchDirects (pa1.c:280)
==19923== by 0x401451: main (pa1.c:339)
==19923== Address 0x585b720 is 0 bytes inside a block of size 27 free'd
==19923== at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19923== by 0x401144: newFile (pa1.c:246)
==19923== by 0x401260: searchDirects (pa1.c:280)
==19923== by 0x401382: directoryCheck (pa1.c:312)
==19923== by 0x4012CD: searchDirects (pa1.c:290)
==19923== by 0x401451: main (pa1.c:339)
==19923== Block was alloc'd at
==19923== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==19923== by 0x52F47D7: vasprintf (vasprintf.c:73)
==19923== by 0x52D3A56: asprintf (asprintf.c:35)
==19923== by 0x40112C: newFile (pa1.c:239)
==19923== by 0x401260: searchDirects (pa1.c:280)
==19923== by 0x401382: directoryCheck (pa1.c:312)
==19923== by 0x4012CD: searchDirects (pa1.c:290)
==19923== by 0x401451: main (pa1.c:339)
在這里,我將其范圍縮小為代碼中的問題:
else
{
currentList = headList;
printf("This is where I will put the code to create the Linked list!\n");
if(currentList != 0)
{
while(currentList->nextList != 0)
{
if(currentList->key = key)
{
asprintf(&buff, "%s %s", currentList->value, dirValue); // PROBLEM IS HERE
printf("Here is the new string that holds the directory paths: %s\n", buff);
currentList->value = buff;
free(buff);
printf("Here is the new string that holds the directory paths: %s\n", currentList->value);
return;
}
currentList = currentList->nextList;
}
currentList->nextList = malloc(sizeof(struct List));
printf("Adding a new node\n");
//Reached the end of the Linked list and didn't find the
//same key so create a new node.
currentList = currentList->nextList;
currentList->key = key;
currentList->nextList = NULL;
currentList->value = dirValue;
}
}
我有很多錯誤,我覺得提供整個valgrind輸出會過大。 我得到的所有錯誤都返回到我使用asprintf()的位置("addToList (pa1.c:124)" line in the report)
。 在代碼上方,我初始化了char *buff = NULL;
,並且currentList->value
包含一個我想使用asprintf附加到的字符串。 對於我為什么會收到大量無效讀取大小1錯誤的任何猜測,將不勝感激。 另外,當我確實打印出asprintf()的結果時,該字符串將按預期追加。
無效的讀取是在已釋放的內存塊的開頭; 您要在釋放內存后嘗試使用內存。
currentList->value = buff;
free(buff);
printf("Here is the new string that holds the directory paths: %s\n", currentList->value);
return;
您使用currentList->value = buff;
在printf()
,但是您剛剛釋放了buff
。 這意味着一場即將來臨的災難。 如果在return
之后將在調用函數中使用currentList->value
,則會遇到重大問題。
您可以通過將printf()
移到free()
printf()
前面來解決一個警告,但是代碼看起來將遇到重大問題。 刪除free(buff);
可能更好free(buff);
-盡管您必須找出實際釋放數據的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.