glibc的fdopen实现是否存在内存泄漏?基于iofdopen.c代码的疑问
关于glibc中iofdopen函数的内存泄漏疑问
在glibc的iofdopen.c文件中,第122行通过malloc创建了new_f对象:
new_f = (struct locked_FILE *) malloc (sizeof (struct locked_FILE));
但在后续第159行附近的返回分支中,当_IO_SYSSEEK调用失败且errno不等于ESPIPE时,直接返回NULL,并未调用free(new_f):
/* For append mode, set the file offset to the end of the file if we added O_APPEND to the file descriptor flags. Don't update the offset cache though, since the file handle is not active. */ if (do_seek && ((read_write & (_IO_IS_APPENDING | _IO_NO_READS)) == (_IO_IS_APPENDING | _IO_NO_READS))) { off64_t new_pos = _IO_SYSSEEK (&new_f->fp.file, 0, _IO_seek_end); if (new_pos == _IO_pos_BAD && errno != ESPIPE) return NULL; }
结论
此处确实存在内存泄漏问题。new_f是通过动态分配得到的内存块,在这个分支中直接返回NULL后,程序失去了对该内存块的引用,无法再通过任何方式释放它,符合内存泄漏的定义——已分配且不再使用的内存无法被系统回收。
虽然glibc作为底层系统库存在一些特殊的内存管理机制,但从标准C内存管理的逻辑来看,这个分支的处理明显遗漏了内存释放操作,属于典型的内存泄漏bug。
内容的提问来源于stack exchange,提问作者simonzgx
相关产品推荐
相关产品推荐

