#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/