【发布时间】:2017-06-18 20:37:12
【问题描述】:
在数组已经存储了来自用户输入的多行后,我不断收到此错误,这告诉我它可能由于该行而损坏了内存:
poemArray = (char **)realloc(poemArray, count + 1);
知道我做错了什么吗?一个具体的解决方案将不胜感激!
line = (char *)malloc(MaxLineLen);
fgets(line, MaxLineLen, stdin);
/*Get current line from user input*/
if(count == 0)
{
poemArray = malloc(sizeof(char *));
printf("1\n");
}
if(line[0] == '.'){
break;
}
line = (char *)realloc(line, strlen(line));
printf("2\n");
if(count != 0)
{
poemArray = (char **)realloc(poemArray, count + 1);
}
poemArray[count] = line;
++count;
【问题讨论】:
-
你可能在后面的代码中读到了
line的结尾;realloc(line, strlen(line))切断了空终止符,所以后面的代码无法知道何时停止阅读 -
line = (char *)realloc(line, strlen(line));是一条毫无意义的行。取已经存在的字符串的长度,然后为它分配空间?呃,什么? -
啊,我明白了,你正在减少线路的分配。在这种情况下,您忘记了所有 C 字符串上终止零的
+ 1。
标签: c arrays pointers memory realloc