问题描述
大家好, Hi All, 这篇关于反复写入日志文件时出现内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
我写了一个小代码,用于将简单的Line重复写入日志文件.
下面是我的代码
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推荐答案