当我尝试将文件作为数组加载到内存中时遇到问题。
我正在尝试将文件加载到数组中并再次打印出来,但我希望允许内存增长,因为文件长度可以是任意的。
当我在 Mac 上本地运行程序时,它似乎工作正常,但当我在 Ubuntu VM 上尝试时,出现以下错误
realloc():下一个大小无效
中止(核心转储)
我的代码如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **loadfile(char *filename, int *len);
int main(int argc, char *argv[])
{
if (argc == 1)
{
printf("Usage add file\n");
return 1;
}
int length = 0;
char **words = loadfile(argv[1],&length);
printf("%d\n", length);
for (int i = 0; i < length; i++) {
printf("%s\n",words[i]);
}
printf("Done\n");
return 0;
}
char **loadfile(char *filename, int *len)
{
const int STEPSIZE = 10;
FILE *f = fopen(filename,"r");
if (!f) {
fprintf(stderr, "Can't open file\n");
return NULL;
}
int arrlen = STEPSIZE;
char **lines = (char **)malloc(STEPSIZE);
char buf[100];
int i = 0;
int counter = 2;
while (fgets(buf,100,f))
{
if (i == arrlen)
{
counter++;
arrlen += STEPSIZE;
char **newlines = (char **)realloc(lines,counter * STEPSIZE);
if(!newlines)
{
printf("Out of memory\n");
//return 2;
}
lines = newlines;
}
buf[strlen(buf)-1] = '\0';
int slen = strlen(buf);
char *str = (char *)malloc(slen + 1 *sizeof(char ));
strcpy(str, buf);
lines[i] = str;
i++;
}
*len =i;
return lines;
}
我一生都找不到问题所在。
我只能假设问题出在本节中的某个地方,但我可能是错的:
if (i == arrlen)
{
counter++;
arrlen += STEPSIZE;
char **newlines = (char **)realloc(lines,counter * STEPSIZE);
if(!newlines)
{
printf("Out of memory\n");
//return 2;
}
lines = newlines;
}
非常感谢您的帮助
最佳答案
const int STEPSIZE = 10;
char **lines = (char **)malloc(STEPSIZE);
char **newlines = (char **)realloc(lines,counter * STEPSIZE);
您不想分配 10 个字节,而是分配 10 个 char * 元素的内存。因此,对 lines[i] = str;
的某些后续访问无效。
你想做的是:
char **lines = malloc(sizeof(*lines) * STEPSIZE);
char **newlines = realloc(lines, sizeof(*newlines) * counter * STEPSIZE);
或者您可以使用sizeof(char*)
。
另外:
char *str = (char *)malloc(slen + 1 *sizeof(char ));
虽然它是正确的并且会起作用,因为 sizeof(char)
是 1,但更清楚的意图是:
char *str = malloc((slen + 1) * sizeof(char));
另外,想想也很好if you should cast the result of malloc .
关于c - 如何修复 realloc() : invalid next size in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58816574/