我正在使用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);
(本质上分配了8x(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 capacityn", a->capacity);
destroyArray (a);
return 0;
}
(注意:在尝试使用array
之前,您还应该验证Array *array = malloc (sizeof *array);
成功和(array != NULL)
(
内存使用/错误检查
$ 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)
看事物,让我知道这是否是您所关心的。