多次使用后 realloc 失败

realloc failing after multiple uses

#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);

你在第一次重新分配时分配了两个 字节 ,然后是三个字节 ....,而不是 space 两个,三个 ... 指针

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

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

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

test[i] = string; 不会为字符串分配 space 并且不会复制它。

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

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

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