Недопустимое чтение размера 1 при использовании 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. Будем весьма благодарны за любые предположения, почему я получаю многочисленные ошибки Invalid read size 1. Кроме того, строка добавляется, как и ожидалось, когда я распечатываю результат из asprintf() Спасибо.

1 ответ

Решение

Недопустимое чтение находится в начале уже освобожденного блока памяти; Вы пытаетесь использовать память после того, как освободили ее.

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, Это означает надвигающуюся катастрофу. Если currentList->value будет использоваться в вызове функций после returnУ вас есть серьезные проблемы.

Вы можете исправить одно предупреждение, перемещая printf() перед free(), но код выглядит так, как будто у вас возникнут серьезные проблемы. Может быть, лучше удалить free(buff); - хотя вы должны были бы решить, где данные фактически освобождены вместо этого.

Другие вопросы по тегам