使用realloc时数据已损坏

问题描述

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

编辑:现在,我已经确定了重新分配的目标,我从重新分配中遇到了内存泄漏。

==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 */
}