gpt4 book ai didi

c - 为什么我的动态字符串数组会泄漏?

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:18 26 4
gpt4 key购买 nike

我需要一个字符串数组,它可以在添加更多项目时动态调整大小。我的基本代码可以正常工作,但 valgrind 报告内存泄漏。

应该使用静态和动态分配的字符串的实现如下所示:

typedef struct {
char **items;
int num;
} StringArray;

StringArray* string_array_init() {
StringArray *arr = malloc(sizeof(StringArray));
arr->items = NULL;
arr->num = 0;
return arr;
}

void string_array_add(StringArray *arr, char *str, int str_len) {
void *new_items = realloc(arr->items, (arr->num + 1) * sizeof(char *));

arr->items = (char**)new_items;
arr->items[arr->num] = strndup(str, str_len);
arr->num++;
}

void string_array_cleanup(StringArray *arr) {
int i;

for (i = 0; i < arr->num ; i++) {
free(arr->items[i]);
}

free(arr);
}




int main() {
StringArray *arr = string_array_init();

string_array_add(arr, "item 1", strlen("item 1"));
string_array_add(arr, "item 2", strlen("item 2"));
string_array_add(arr, "item 3", strlen("item 3"));

string_array_cleanup(arr);

return 0;
}

Valgrind 报告:

==31443== HEAP SUMMARY:
==31443== in use at exit: 12 bytes in 1 blocks
==31443== total heap usage: 7 allocs, 6 frees, 53 bytes allocated
==31443==
==31443== 12 bytes in 1 blocks are definitely lost in loss record 1 of 1
==31443== at 0x4025CCD: realloc (vg_replace_malloc.c:525)
==31443== by 0x80484A6: string_array_add (in ...)
==31443== by 0x8048593: main (in ...)
==31443==
==31443== LEAK SUMMARY:
==31443== definitely lost: 12 bytes in 1 blocks
==31443== indirectly lost: 0 bytes in 0 blocks
==31443== possibly lost: 0 bytes in 0 blocks
==31443== still reachable: 0 bytes in 0 blocks
==31443== suppressed: 0 bytes in 0 blocks
==31443==

为什么 realloc 会泄漏,我该如何修复它?我认为分别释放每个字符串然后释放结构就足够了,但我遗漏了一些东西。

最佳答案

您释放了 arr->items 中包含的字符串,但您没有释放 arr->items 本身。 (您在 string_array_add 中分配了它)。

关于c - 为什么我的动态字符串数组会泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7876009/

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