反复写入日志文件时出现内存泄漏 [英] Memory Leak while repeatedly writting to the log file

查看:140
本文介绍了反复写入日志文件时出现内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我写了一个小代码,用于将简单的Line重复写入日志文件.

下面是我的代码

Hi All,
I have written a small code for writting a simple Line to a log file repeatedly.

below is my code

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>

#define LOGFILE "C:\\mem_leak.txt"

int WriteToLog(const char* str,...)
{
  FILE* log;
  va_list ap;
  
  va_start(ap, str);
  log = fopen(LOGFILE, "a+");
  if (log == NULL) {
    return -1;
  }
  vfprintf(log, str, ap);
  fclose(log);
  va_end(ap);
  return 0;
}

int main() {
  static int i =0;
  while (1) {
    if (-1 == WriteToLog("Memory Leak [%d]\n", ++i)) {
      return -1;
    }
    Sleep(5);
  }
  return 0;
}



但是运行此程序并检查内存使用情况时,其内存使用量会随着时间增加.
是否存在内存泄漏?如果是这样,请在这方面帮助我.

>如果我使用printf而不是将其写入文件,则内存不会随时间增加.如果我在while循环之外打开文件(即while循环之前),然后在while循环之后关闭文件.那么记忆就不会随着时间而增加.

fopen()调用是否存在任何问题?如果我们在while循环中重复使用它?

感谢和问候,
Sandeep Kumar Patra



But when run this program and checked the memory usage, its memory usage increases with time.
Is there any memory leak? If then, please help me in this regard.

> If I use printf instead of writting it to the file, memory does not increases with time

> If I open the file out of the while loop (i.e. before while loop) and closes the file after while loop. then also momory does not increases with time.

Is there any issue with the fopen() call? if we use it repeatedly inside a while loop?

Thanks and Regards,
Sandeep Kumar Patra

推荐答案

乍一看对我来说还可以.您为什么认为它泄漏?当您观察到内存使用量随时间增加"时,您正在查看哪个指标.您观察什么特定的内存指标?它有多大?如果最小化窗口(修剪工作集)会发生什么?

looks okay to me at first glance.  Why do you think it leaks?  Which metric are you looking at when you observe that "memory usage increases with time."  What specific memory metric are you observing?  How large does it get?  what happens if you minimize the window (which trims the working set)?


这篇关于反复写入日志文件时出现内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆