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

标签 c arrays command-line free

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

    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 仅对第一个文件为 null。对 getline() 的调用将 line 设置为指向随后被释放的内容。

下一次 line 的值不再是 null 而是指向一个不应被写入的已释放位置,然后 free 在先前被释放的相同值上再次调用.

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

free(line);
line = NULL;

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

关于c - 读取多个文本文件(或执行两次?)时出现 free() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50094434/

相关文章:

c - 将变量移动到 cl 并使用内联汇编执行 shr

python - 实参校验性能影响

objective-c - 游戏实体的类型和子类型的良好模式或架构?

c - 数组操作(插入元素)

c++ - 是否可以通过运算符重载按索引分配用户定义的数组? - C++

PHP 在 foreach 中单独求和值

java - 如何在 java 中从字符串创建 args[]

python - Python 会很好地替代 Windows 命令行/批处理脚本吗?

c - 无法从 C 中的结构中打印字段

Android 项目和 Gradle : assemble a single module