内存泄漏在哪里?

时间:2020-05-04 15:34:11

标签: c valgrind

一段时间以来,我一直在使用此字典的“拼写检查”功能,并最终使其完全正常运行,除了一个小错误,即不知道该内存泄漏在哪里。当我运行valgrind时会出现:

> ==793== Memcheck, a memory error detector
> ==793== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
> ==793== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
> ==793== Command: ./speller texts/cat.txt
> ==793== 
> 
> MISSPELLED WORDS
> 
> ==793== Conditional jump or move depends on uninitialised value(s)
> ==793==    at 0x520A60F: tolower (ctype.c:46)
> ==793==    by 0x4010E2: check (dictionary.c:37)
> ==793==    by 0x400CD9: main (speller.c:112)
> ==793==  Uninitialised value was created by a stack allocation
> ==793==    at 0x4008E4: main (speller.c:21)
> ==793== 
> ==793== Use of uninitialised value of size 8
> ==793==    at 0x520A623: tolower (ctype.c:46)
> ==793==    by 0x4010E2: check (dictionary.c:37)
> ==793==    by 0x400CD9: main (speller.c:112)
> ==793==  Uninitialised value was created by a stack allocation
> ==793==    at 0x4008E4: main (speller.c:21)
> ==793== 
> 
> WORDS MISSPELLED:     0 WORDS IN DICTIONARY:  143091 WORDS IN TEXT:   
> 6 TIME IN load:         1.44 TIME IN check:        0.05 TIME IN size: 
> 0.00 TIME IN unload:       0.19 TIME IN TOTAL:        1.69
> 
> ==793== 
> ==793== HEAP SUMMARY:
> ==793==     in use at exit: 552 bytes in 1 blocks
> ==793==   total heap usage: 143,096 allocs, 143,095 frees, 8,023,416 bytes allocated
> ==793== 
> ==793== 552 bytes in 1 blocks are still reachable in loss record 1 of 1
> ==793==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
> ==793==    by 0x5258E49: __fopen_internal (iofopen.c:65)
> ==793==    by 0x5258E49: fopen@@GLIBC_2.2.5 (iofopen.c:89)
> ==793==    by 0x401211: load (dictionary.c:77)
> ==793==    by 0x4009B4: main (speller.c:40)
> ==793== 
> ==793== LEAK SUMMARY:
> ==793==    definitely lost: 0 bytes in 0 blocks
> ==793==    indirectly lost: 0 bytes in 0 blocks
> ==793==      possibly lost: 0 bytes in 0 blocks
> ==793==    still reachable: 552 bytes in 1 blocks
> ==793==         suppressed: 0 bytes in 0 blocks
> ==793== 
> ==793== For counts of detected and suppressed errors, rerun with: -v
> ==793== ERROR SUMMARY: 8 errors from 2 contexts (suppressed: 0 from 0)

很抱歉发布整个内存消息,但是我不确定Valgrind消息的哪一部分有错误的位置。

下面是发生错误的C代码,我假设它在加载或卸载函数中。

```C

//for the universal hash function
#define BASE 256

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Number of buckets in hash table
const unsigned int N = 676;

// Hash table
node *table[N];
int word_count = 0;

// Returns true if word is in dictionary else false
//Require a search funtion
bool check(const char *word)
{
    //change to lower case to compare
    char low[LENGTH + 1];
    
    for (int i = 0, n = strlen(word); i <= (n + 1); i++)
    {
        low[i] = tolower(word[i]);
    }
    
    int hashIndex = hash(low);
    for (node *tmp = table[hashIndex]; tmp != NULL; tmp = tmp->next)
    {
        
        if (strcasecmp(low, tmp->word) == 0)
        {
            return true;
        }
    }
    return false;
}

// Hashes word to a number
// the dividing hash function is one I cited from the yale.edu page http://www.cs.yale.edu/homes/aspnes/pinewiki/C(2f)HashTables.html having worked with.
unsigned int hash(const char *word)
{
    unsigned long m = 11;
    unsigned long h;
    unsigned const char *us;
    //ensure element value is >= 0 
    us = (unsigned const char *) word;

    h = 0;
    while(*us != '\0') 
    {
        h = (h * BASE + *us) % m;
        us++;
    } 
    return (h % N);
}

// Loads dictionary into memory, returning true if successful else false
//Bring the used sictionary to menu asap
bool load(const char *dictionary)
{
    
    // Open file and check file 
    FILE *file = fopen(dictionary, "r");
    if (!file)
    {
        return false;
    }
    
    
    //array declaration for fscanf to read into
    char word[LENGTH + 1];
    while (fscanf(file, "%s", word) == 1)
    {
        //Create node n = new node
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            printf("No memory for node\n");
            fclose(file);
            return false;
            
        }
        strcpy(n->word, word);
        
        //Hash the word
        int hashDigit = hash(word);
        //Insert into the beginning of the list
        if (table[hashDigit] == NULL)
        {
            table[hashDigit] = n;
            n->next = NULL;
        }
        else
        {
            n->next = table[hashDigit];
            table[hashDigit] = n;
        }
        word_count++;
    }
    return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
//count the amount of words in dictionary
unsigned int size(void)
{
    
    return word_count;
}

// Unloads dictionary from memory, returning true if successful else false
//free the dictionary from memory asap
bool unload(void)
{
    //Loop to run through array
    for (int i = 0; i < N; i++)
    {
        //to target linked list
        while (table[i] != NULL)
        {
            node *tmp = table[i];
            table[i] = table[i]->next;
            free(tmp);
        }
    }
    
    return true;
}

据我所知,我已经尝试正确地释放了所有的内存,并从第36行的“有条件的跳转或移动取决于未初始化的值”中出现了,但是我不确定这恰好意味着或如何解决该问题。

我希望获得一些有关如何更好地做到这一点的建议。

4 个答案:

答案 0 :(得分:3)

它会泄漏您从FILE*获得的fopenfclose丢失。

这是valgrind告诉您的地方:

==793== 552 bytes in 1 blocks are still reachable in loss record 1 of 1
==793==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==793==    by 0x5258E49: __fopen_internal (iofopen.c:65)
==793==    by 0x5258E49: fopen@@GLIBC_2.2.5 (iofopen.c:89)
==793==    by 0x401211: load (dictionary.c:77)
==793==    by 0x4009B4: main (speller.c:40)

fopen最终调用malloc来分配FILE,它必须与fclose一起释放,而free最终在该FILE*上调用Conditional jump or move depends on uninitialised value。 / p>


for (int i = 0, n = strlen(word); i <= (n + 1); i++) low[i] = tolower(word[i]); 警告是由以下原因引起的:

i <= n

该循环从零终止符处读取一个额外的字符。它需要修复:i < (n + 1)a = 1

答案 1 :(得分:2)

> ==793== 552 bytes in 1 blocks are still reachable in loss record 1 of 1
> ==793==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
> ==793==    by 0x5258E49: __fopen_internal (iofopen.c:65)
> ==793==    by 0x5258E49: fopen@@GLIBC_2.2.5 (iofopen.c:89)
> ==793==    by 0x401211: load (dictionary.c:77)
> ==793==    by 0x4009B4: main (speller.c:40)

泄漏是来自fopen,因为您没有打电话给fclose

答案 2 :(得分:0)

您在此处创建了大量指针

node *table[N];

但是您永远不要将该数组设置为NULL。

然后,假设该数组已初始化,您可以对该数组进行各种处理。

答案 3 :(得分:0)

我遇到了同样的问题(哈佛 CS50 课程第 5 周),但上面的答案只让我成功了一半。

最终通过将空终止符 '\0' 显式分配给每个单词的剩余字符来解决它,如下所示:

    for (int i = 0; i < LENGTH + 1; i++) {
        low[i] = (i < strlen(word)) ? tolower(word[i]) : '\0';
    }
相关问题