读取多个文本文件(或执行两次?)时出现 free() 问题

Issue with free() when reading multiple text files (or executed twice?)

在读取多个文件时,我的代码的某个部分遇到了问题。这是大部分内容:

    char *a;
    int ch;
    char *line = NULL;
    char *prev_line[999];
    size_t len = 0;
    size_t read;
    if (argc > 1)
    {
      int i = 1;
      FILE *fp;
      while (i < argc)
      {
          a = malloc (MAX_NAME_SZ * sizeof (char));
          fp = fopen (argv[i], "r");
          if (fp == NULL)
          {
              /*Error statement in case an file doesn't exist */
          }
          else
          {
              while ((read = getline(&line, &len, fp)) != -1) {
                  if (strncmp(line, prev_line, read) != 0) {
                      strncat(a, line, read);
                      strncpy(prev_line, line, read);          
                  }
              }
              free(line); 

              fclose (fp);
              changeCase (a);
              printf ("\n");

          }
          i++;            
      }  
   }
   else
   {
       a = malloc (MAX_NAME_SZ * sizeof (char));
       fgets (a, MAX_NAME_SZ, stdin);
       changeCase (a);
       printf ("\n");
    }
}

但我的问题包括这一部分。

while ((read = getline(&line, &len, fp)) != -1) {
    if (strncmp(line, prev_line, read) != 0) {
        strncat(a, line, read);
        strncpy(prev_line, line, read);          
    }
}
free(line); 

这部分代码只读取与上一行不同的行。但是,当我有多个参数并且此代码经过两次时,我会收到双重释放或损坏错误,我认为这是因为 free(line) 完成了两次。

代码中是否有其他地方我应该移动它,或者我可以用什么来替换它?

根据 getline() documentation:

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program.

在您的情况下,line 仅对第一个文件为空。对 getline() 的调用将 line 设置为指向随后被释放的对象。

下一次,line 的值不再为 null,而是指向不应写入的已释放位置,然后再次调用 free 之前释放的相同值。

释放后将 line 设置回 NULL 应该可以解决您的问题。

free(line);
line = NULL;

这应该会导致 getline() 为每个正在读取的文件分配新内存。