while循环中的内存泄漏

时间:2014-12-25 10:41:20

标签: c memory-leaks struct while-loop

此代码存在内存泄漏但我无法找到它。它逐行读取并保存一些返回值。以下代码也在while(1)循环上,它读取文件并等待几秒钟然后重新读取。

  while ((read = getline(&line, &len, fp)) != -1) {
    struct matches matched = check_match(line,lgd,grd);
    if (matched.status>=1)//ali 1 ni taarsan
    {
      timelog1[y] = calloc(strlen(matched.timelog),  sizeof(char));
      strcpy(timelog1[y] ,matched.timelog);
      messages1[y] = calloc(strlen(matched.message), sizeof(char));
      strcpy(messages1[y],matched.message);
      y++;
    }
  }

这里struct匹配

struct matches
{
  char *timelog;
  // char *groups[maxgroup];
  const char *message;       //messaguud hadgalana
  int setting;
  int status;    
};

功能是:

struct matches check_match(char * input,struct log_data lgd,struct group_data grd);

我宣布时间日志和消息如下:

char **timelog1 = calloc(maxline, sizeof(char*));
char **messages1 = calloc(maxline, sizeof(char*));
  

MAXLINE = 15000

我在哪里泄露记忆?

更新

对不起,我从行

读完后释放了如下内容
  for (i = 0; i < count; ++i)
  {
    free(timelog1[i]);
    free(messages1[i]);
  }

1 个答案:

答案 0 :(得分:2)

calloc(strlen(matched.timelog), sizeof(char));

strlen是不够的,你需要为空终结符留出空间,你想要分配strlen(matched.timelog) + 1。与其他calloc电话相同。