簡體   English   中英

Valgrind Memory 泄漏,無效的免費()

[英]Valgrind Memory Leaks, Invalid free()

typedef struct {
   int **a;
   int **b;
   int **c;
   int i;
} test_t;

test_t *create(int i) {
    test_t *test = malloc(i * sizeof(test_t));

    test->i = i;

    test->c = malloc(i * sizeof(int *));
    for (int j = 0; j < i; ++j) {
        test->c[j] = malloc(sizeof(int *));
    }

    test->a = malloc(sizeof(int *));
    test->a = &(test->c[0]);
    test->b = malloc(sizeof(int *));
    test->b = &(test->c[0]);
    return test;
}

void delete(test_t *test) {
    free(test->a);
    free(test->b);
    for (int i = 0; i < test->i; ++i)
        free(test->c[i]);
    free(test->c);
    free(test);
}

int main() {
    test_t *test;

    test = create(3);

    delete(test);

    return 0;
}

這段代碼有什么問題?

當我運行 Valgrind 時,我得到 5 個錯誤和一些 memory 泄漏。

我沒有看到任何 memory 泄漏,是嗎?

我收到如下錯誤:

Invalid free() / delete / delete[] / realloc()
Address 0x4a380e0 is 0 bytes inside a block of size 24 free'd
Block was alloc'd at
Invalid read of size 8

請問有人可以幫我嗎?

PS 代碼工作正常,但它有 memory 泄漏,所以它沒有。

目不轉睛...

    test->a = malloc(sizeof(int *));
    test->a = &(test->c[0]);
    test->b = malloc(sizeof(int *));
    test->b = &(test->c[0]);

由於test->atest->b立即重新分配,因此 malloc 沒有任何作用,除了泄漏 memory。 以上應該很簡單...

    test->a = &(test->c[0]);
    test->b = &(test->c[0]);

有了這個經驗法則,mallocs 的數量應該等於 frees 的數量。 三個 malloc,一個循環。 三個釋放,一個循環。

void delete(test_t *test) {
    for (int i = 0; i < test->i; i++) {
        free(test->c[i]);
    }
    free(test->c);
    free(test);
    test->a = NULL;
    test->b = NULL;
}

test->atest->b不應被釋放,因為它們正在借用test->c[0]的 memory。 我們也需要避免兩次釋放它。 既然借來的memory是無效的,不能再用了,我們把它設置為NULL萬一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM