如何修复 realloc():C 中的下一个大小无效

How do I fix realloc(): invalid next size in C

当我尝试将文件作为数组加载到内存中时遇到问题。

我正在尝试将文件加载到数组中并再次打印出来,但我想允许内存增长,因为文件长度可以是任意的。

当我在我的 Mac 本地 运行 我的程序时它似乎工作正常但是当我在我的 Ubuntu VM 上尝试它时,我收到以下错误 realloc(): invalid next size
Aborted (core dumped)

我的代码如下

#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] = '[=10=]';

    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

您忘记了 malloc 和 realloc 占用的字节数,而不是数组中 'cells' 的字节数。

如果您将 malloc(STEPSIZE) 替换为 malloc(STEPSIZE * sizeof(char*)) 并将 realloc(lines, counter * STEPSIZE) 替换为 realloc(lines, (counter * STEPSIZE) * sizeof(char*))

,程序将按预期运行