c - 多次使用后 realloc 失败

标签 c malloc realloc

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    char string[10];
    int count = 0;
    int buff = 1;
    int i = 0;
    char **test = malloc(sizeof(char*) * buff);

    while (1) {
        scanf("%s", string);
        count++;
        if (count > buff) {
            buff += buff;
            test = realloc(test, buff);
            test[i] = string;
            i++;
        }
        else {
            test[i] = string;
            i++;
        }
    }
}

这只是一个更大项目的一些测试代码,我正在处理同样的问题(因此为什么 buff 这么小)。我不确定为什么 realloc() 在 ~2-3 次调用后失败。任何想法?

最佳答案

 test = realloc(test, buff);

你在第一个 realloc 上分配了两个 bytes,然后是三个字节......,而不是两个,三个...... pointers

您的程序只是一个巨大的未定义行为

 test = realloc(test, buff * sizeof(*test));

顺便说一句,所有分配的指针将指向内存中的同一个地方

test[i] = string; 不为字符串分配空间,也不复制它。

test[0] == test[1] == test[2] .... ==test[n] 最后扫描的字符串

要存储所有扫描输入的字符串,您需要分配内存并复制字符串

test[i] = malloc(strlen(string) + 1);
strcpy(test[i], string);

关于c - 多次使用后 realloc 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54854857/

相关文章:

c - 无效数组上的qsort *

c - 改进我执行 malloc 和 free 的方式

c - 如果在循环中多次调用 malloc() 和 realloc() 则多次 free()ing

c++ - 如何重新分配内存,即使 c++ 中的 realloc() 失败

c - 释放重新分配导致错误

c - 向 libbluray 添加函数时 undefined reference

c - 如何从c中的数组中排序日期

c - 如何 malloc 预处理器指令

c - 从 scanf 获取任意数量的参数

java - 声明与其定义类型相同的结构变量