使用 realloc() 时数据被破坏

Data being corrupted when using realloc()

在 class 的项目中,我需要增加空指针动态数组的容量。目前我在使用 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

有什么想法是从哪里来的吗?

存在多个问题:

  • 您不是在重新分配元素数组,而是在重新分配 dynarray 结构本身。
  • 如果您重新分配数组,则不会存储该元素:如果像您那样分隔 else 子句很容易出错。
  • 您不检查 0 初始容量:cap * 2 仍然是 0

这是修改后的版本:

#include <stdlib.h>

struct dynarray {
    void **data;
    int size;
    int capacity;
};

int dynarray_insert(struct dynarray *da, void *val) {
    int size = da->size;
    int cap = da->capacity;

    if (size == cap) {            /* if there is no more room */
        cap = cap ? cap * 2 : 8;  /* double capacity, special case for zero */
        void **temp = realloc(da->data, sizeof(void *) * cap);
        if (temp == NULL) {
            return -1;   /* return -1 upon realloc failure */
        }
        da->cap = cap;
        da->data = temp;
    }
    da->data[size] = val;
    return da->size++;   /* return the index of the new element if successful */
}