【发布时间】:2021-02-01 01:56:36
【问题描述】:
在一个类项目中,我需要增加 void 指针的动态数组的容量。目前我在使用 realloc 时遇到了损坏用户数据的问题。
void dynarray_insert(struct dynarray* da, void* val) {
int i;
int size = da->size;
int cap = da->capacity;
/*if there is no more room*/
if (size == cap) {
cap = cap * 2; /*double capacity*/
void** temp = realloc(da, sizeof(void*) * cap);
da->data = temp;
}
/*if there is room*/
else if (size < cap) {
da->data[size] = val;
}
size++;
da->size = size;
da->capacity = cap;
return;
}
有我目前的增容功能代码,
struct dynarray {
void** data;
int size;
int capacity;
};
这是 dynarray 结构。
编辑:现在我修复了 realloc 的目标,我有一个来自 realloc 的内存泄漏。
==474== HEAP SUMMARY:
==474== in use at exit: 64 bytes in 1 blocks
==474== total heap usage: 15 allocs, 14 frees, 848 bytes allocated
==474==
==474== 64 bytes in 1 blocks are definitely lost in loss record 1 of 1
==474== at 0x483DFAF: realloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==474== by 0x1098E3: dynarray_insert (dynarray.c:96)
==474== by 0x109303: test_dynarray (test_dynarray.c:39)
==474== by 0x1097B6: main (test_dynarray.c:136)
==474==
==474== LEAK SUMMARY:
==474== definitely lost: 64 bytes in 1 blocks
==474== indirectly lost: 0 bytes in 0 blocks
==474== possibly lost: 0 bytes in 0 blocks
==474== still reachable: 0 bytes in 0 blocks
==474== suppressed: 0 bytes in 0 blocks
任何想法可能来自哪里?
【问题讨论】:
-
如果
realloc(da, sizeof(void*) * cap);成功,则不再允许您访问da- 因此下一行(da->data = temp;)调用未定义行为。虽然这部分代码看起来很奇怪,但你想在这里做什么? -
第二次看我怀疑你想
realloac(da->data而不是da?
标签: c malloc dynamic-arrays realloc