重复使用文件指针会导致内存泄漏吗?
自从我处理 C++ 以来已经有好几年了,所以请耐心等待...
我的程序中存在内存泄漏,导致运行时错误。这可能会导致错误吗?
我有一个全局变量 FILE *fp;
在回调函数中,我有:
fp = fopen(filen,"w");
// do some writing
fclose(fp);
使用相同的指针(fp)重复此过程多次。使用相同的文件指针有问题吗? fclose() 会自动为我释放内存,还是需要手动删除它?如果我编写大量文本,是否存在可能导致运行时错误的限制?
谢谢!
It's been several years since I've dealt with C++, so bear with me...
I have a memory leak in my program which causes a run-time error. Could this be causing the error?
I have a global variable FILE *fp;
In a callback funciton, I have:
fp = fopen(filen,"w");
// do some writing
fclose(fp);
This process is repeated several times with the same pointer (fp). Is using the same file pointer a problem? Will fclose() automatically free up memory for me, or do I need to delete it manually? Are there any limitations that might cause a run-time error if I'm writing large quantities of text?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,
fclose
释放与FILE *
关联的所有资源。根据经验,仅对使用malloc
分配的内容使用free
,仅对使用new 分配的内容使用
。delete
而且您永远不会“重用”同一个指针:调用
fopen
将返回一个新的FILE *
。顺便说一句,由于您正在使用 C++,请考虑研究一下
fstream
。它将为您处理资源管理。Yes,
fclose
releases all resources associated with theFILE *
. As a rule of thumb, only usefree
on what was allocated withmalloc
, and only usedelete
on what was allocated withnew
.And you're never "reusing" the same pointer: a call to
fopen
will return a newFILE *
.By the way, since you're doing C++, consider looking into
fstream
. It'll handle the resource management for you.只要
fopen
在下一次fopen
调用之前始终跟随着fclose
,这种方法就不会导致任何内存泄漏。然而,如果这确实是发生的事情,我会质疑是否需要全局变量。总体而言,将其设为本地并将其传递给需要输出信息的函数会更安全。
This approach won't cause any memory leaks so long as the
fopen
is always followed by afclose
before the nextfopen
call.However if this is indeed what's happening I would question the need for a global variable. It's much safer overall to make this a local and pass it around to the functions which need to output information.
听起来你做的事情完全正确 -
fclose
应该逆转fopen
所做的一切,包括释放它可能分配的任何资源。It sounds like you're doing things exactly correctly --
fclose
should reverse whateverfopen
does, including freeing any resources it might allocate.多个线程访问同一全局可能会导致其中一个线程关闭文件后出现的问题。
随后打开文件并更改文件指针时,不会看到这种情况。
关闭文件只会关闭 1 个已创建的文件句柄,从而导致文件句柄泄漏,并且对该文件的任何进一步写入都将失败,并且同一句柄上的后续关闭文件尝试第二次关闭它可能会崩溃(如果不这样做)已经发生写入文件的情况。
Multiple threads hitting the same global could cause an issue that would appear after one of the threads closed the file.
Opening the file a subsequent time and changing the file pointer wouldn't be seen when it happened.
Closing the file would only close 1 of the created file handles leaving a file handle leak and any further writes to the file would fail and a subsequent close file on the same handle trying to close it a second time would likely crash if it didn't already happen writing to the file.