使用 malloc 时出现 Valgrind 错误

Valgrind error when using malloc

我正在使用 valgrind 修复我的 C 程序中的内存泄漏,并且有一个特定的函数似乎是大多数 valgrind 错误的来源

typedef struct Array {
    int capacity;
    int size;
    void **items;
} Array;

Array *createArray(int capacity) {
    Array *array = malloc(sizeof(Array));
    array->capacity = capacity;
    array->size = 0;
    void **items = malloc(sizeof(void *) * array->capacity *  sizeof *items);
    if(items == NULL) {
        exit(1);
    }
    array->items = items;
    return array;
}

createArray 函数的第一行在 Valgrind 中抛出以下错误

1,296 (16 direct, 1,280 indirect) bytes in 1 blocks are definitely lost in loss record 34 of 42

我是否没有以正确的方式使用 malloc 来分配内存?

正如上面评论中所讨论的,不清楚你为什么分配 items 与:

 void **items = malloc(sizeof(void *) * array->capacity *  sizeof *items);

(实际上分配的指针数量是所需数量的 8 倍(sizeof "a pointer" 的额外倍数)

相反,如果您为 items 分配 array->capacity 指针,则使用:

void **items = malloc(array->capacity * sizeof *items);

你的 valgrind 错误看起来不像是错误,而是没有在你分配的内存上调用 free 的结果,留下 valgrind 报告丢失的字节(仍然可以访问退出时)。您可以使用类似于以下的简单 destroyArray 函数在退出时轻松释放内存:

void destroyArray (Array *array) {
    for (int i = 0; i < array->size; i++)
        free (array->items[i]);
    free (array->items);
    free (array);
}

总而言之,您可以执行以下操作:

#include <stdio.h>
#include <stdlib.h>

typedef struct Array {
    int capacity;
    int size;
    void **items;
} Array;

Array *createArray (int capacity) {
    Array *array = malloc (sizeof *array);
    array->capacity = capacity;
    array->size = 0;
    void **items = malloc(array->capacity *  sizeof *items);
    if(items == NULL) {
        exit(1);
    }
    array->items = items;
    return array;
}

void destroyArray (Array *array) {
    for (int i = 0; i < array->size; i++)
        free (array->items[i]);
    free (array->items);
    free (array);
}

int main (void) {

    Array *a = createArray (10);
    printf ("%d capacity\n", a->capacity);
    destroyArray (a);

    return 0;
}

(注意: 你还应该在尝试使用 array 之前验证 Array *array = malloc (sizeof *array); 成功和 (array != NULL))

内存Use/Error检查

$ valgrind ./bin/allocstruct
==5777== Memcheck, a memory error detector
==5777== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5777== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==5777== Command: ./bin/allocstruct
==5777==
10 capacity
==5777==
==5777== HEAP SUMMARY:
==5777==     in use at exit: 0 bytes in 0 blocks
==5777==   total heap usage: 2 allocs, 2 frees, 96 bytes allocated
==5777==
==5777== All heap blocks were freed -- no leaks are possible
==5777==
==5777== For counts of detected and suppressed errors, rerun with: -v
==5777== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

检查一下,让我知道这是否是您关心的问题。