gpt4 book ai didi

无法释放 C 中的一些内存

转载 作者:行者123 更新时间:2023-11-30 18:54:51 25 4
gpt4 key购买 nike

我正在开发哈希表 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”函数中的两个malloc。程序中的所有其他 malloc 都已释放,因此这是唯一需要释放的。有什么想法吗?

最佳答案

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

然后你需要将它们全部释放。

In order to overcome memory leak you need to free() all memory allocated using malloc() calloc() and realloc()

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

关于无法释放 C 中的一些内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29487103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com