使用malloc时Valgrind错误

时间:2018-02-21 06:25:22

标签: c malloc valgrind

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

server.port=0

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; } 函数的第一行是在Valgrind中抛出以下错误

createArray

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

1 个答案:

答案 0 :(得分:2)

正如上面评论中所讨论的,目前还不清楚为什么要将items分配给:

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

(基本上分配8x(sizeof "a pointer"的额外倍数)指针数量)

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

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 = malloc (sizeof *array);之前,您还应该验证(array != NULL)成功和array

内存使用/错误检查

$ 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)

仔细看看,如果这是你所关注的话,请告诉我。