C、double数组和char数组realloc的区别

C. The difference between realloc in double array and char array

我必须动态增加双精度数组的长度。我知道,如何使用 char 数组来做到这一点,所以我尝试了这个:

int main() {
    char * tmp = NULL;
    for (int i = 1; i <= 4; i++) {
        tmp = realloc(tmp, i * sizeof(char));
        tmp[i] = 'i';
    }
    puts("char OK");
    double * tmp1 = NULL;
    for (int i = 1; i <= 4; i++) {
        tmp1 = realloc(tmp1, i * sizeof(double));
        tmp1[i] = 0;
    }
    return 0;
}

第一个数组工作正常。但是第二个消息 realloc(): invalid next size.

这是我的 2 个问题:

  1. 为什么这种方式在双数组中不起作用?
  2. 如何动态地增加双精度数组的大小?

更新: 删除了错别字

TL;DR: 两个片段都是错误的,第一个 似乎 因为 undefined behavior 而起作用。

详细来说,问题出在您的索引逻辑上。 C 使用基于 0 的索引。因此,在从 i 的值作为 1 开始迭代的循环中,通过使用

 tmp[i] = .......

您正在尝试访问无效内存,此时,最多只能访问 tmp[i-1]

你需要用到tmp1[i-1] = 0;,同理


也就是说,

  1. 在使用 returned 指针之前,始终检查内存分配器函数是否成功。
  2. 永远不要使用表格

      pointer = realloc (pointer, ......)
    

    因为,如果 realloc 调用失败,您最终也会丢失原始指针。

    引用 C11,章节 §7.22.3.5

    The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.

    [....] If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

    • 始终使用临时指针变量来存储 realloc()
    • 的 return 值
    • 检查调用是否成功 [not-null return value] 和
    • 如果需要,然后将其重新分配给原始变量。