无法在C中释放一些内存

时间:2015-04-07 08:27:51

标签: c memory valgrind

我正在研究哈希表C程序。我在以下函数中只有1个内存泄漏:

void put(char *key, char *value, TD* H)
{
    if(!get(key, H))
    {
        int poz = fd(key, H->M);
        CelulaH *aux, *aux2;
        aux = malloc(sizeof(CelulaH));
        aux->key = malloc(50);
        aux->value = malloc(50);
        strcpy(aux->key, key);
        strcpy(aux->value, value);

        if(H->v[poz] == NULL)
        {
            H->v[poz] = (TCelulaG*)malloc(sizeof(TCelulaG));
            H->v[poz]->info = malloc(sizeof(CelulaH));
            memcpy(H->v[poz]->info, aux, sizeof(CelulaH));
            H->v[poz]->urm = NULL;
        }
        else
            InsLGO(&H->v[poz], aux, sizeof(CelulaH), cmp);

        //if(aux)
            free(aux);
    }
}

我有三种结构:TD,CelulaH,TCelulaG。这就是他们的样子:

typedef struct celula
{
    struct celula* urm;
    void* info;
} TCelulaG, *TLG, **ALG;


typedef struct
{
    size_t M;
    TFhash fd;
    TLG *v;
} TD;


typedef struct
{
    char *key, *value;
} CelulaH;  

这是Valgrind的输出:

==5380== Conditional jump or move depends on uninitialised value(s)
==5380==    at 0x8048A2B: get (in /home/luzi/TemaSD/tema1)
==5380==    by 0x8048B26: put (in /home/luzi/TemaSD/tema1)
==5380==    by 0x8048E19: CitireComenzi (in /home/luzi/TemaSD/tema1)
==5380==    by 0x804909E: main (in /home/luzi/TemaSD/tema1)
==5380== 
==5380== Conditional jump or move depends on uninitialised value(s)
==5380==    at 0x8048BB7: put (in /home/luzi/TemaSD/tema1)
==5380==    by 0x8048E19: CitireComenzi (in /home/luzi/TemaSD/tema1)
==5380==    by 0x804909E: main (in /home/luzi/TemaSD/tema1)
==5380== 
==5380== 50 bytes in 1 blocks are definitely lost in loss record 1 of 2
==5380==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==5380==    by 0x8048B60: put (in /home/luzi/TemaSD/tema1)
==5380==    by 0x8048E19: CitireComenzi (in /home/luzi/TemaSD/tema1)
==5380==    by 0x804909E: main (in /home/luzi/TemaSD/tema1)
==5380== 
==5380== 50 bytes in 1 blocks are definitely lost in loss record 2 of 2
==5380==    at 0x402A17C: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==5380==    by 0x8048B73: put (in /home/luzi/TemaSD/tema1)
==5380==    by 0x8048E19: CitireComenzi (in /home/luzi/TemaSD/tema1)
==5380==    by 0x804909E: main (in /home/luzi/TemaSD/tema1)
==5380== 

所以现在看来​​唯一的问题是" put"中的两个mallocs。功能。程序中的所有其他malloc都是免费的,所以这是唯一免费的。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

aux = malloc(sizeof(CelulaH));
aux->key = malloc(50);
aux->value = malloc(50);

然后你需要释放它们。

  

为了克服内存泄漏,您需要free()所有内存   使用malloc() calloc()realloc()

分配
free(aux->value);
free(aux->key);
free(aux);

答案 1 :(得分:0)

结构也可以用在malloc语句中。

您可以在结构上分配内存:

/* Allocate memory */
aux = (CelulaH*)malloc(sizeof(CelulaH));
/* Use variables */
strcpy((*aux).key, key);
strcpy((*aux).value, value);

然后释放它

free(aux);