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

时间:2011-10-24 13:01:20

标签: c arrays memory-leaks

我需要一个字符串数组,当添加更多项时会动态调整大小。我得到了基本代码,但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泄漏,我该如何解决?我决定分开释放每个字符串,然后释放结构就足够了,但我错过了一些东西。

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:-1)

问题在于这一行:

arr->items = (char**)new_items;

您覆盖旧指针。您需要重新分配此指针而不是new_items。