From 6dbf1d10263dbf2f49d12d788f89ab308ba4ca6d Mon Sep 17 00:00:00 2001 From: Mark Adler Date: Thu, 20 Oct 2011 09:07:58 -0700 Subject: [PATCH] Add comment to gzdopen() in zlib.h to use dup() when using fileno(). A problem surfaced in a multi-threaded application where fileno() was used to get a file descriptor from an fopen(), which was then fed to gzdopen(). The problem occurred when the gzclose() followed by the fclose() tried to close the same file descriptor twice. If fclose() were not done, there would be a memory leak. The only way out is to dup() the file descriptor so that gzclose() closes the duplicated file descriptor, and fclose() closes the original file descriptor. --- zlib.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/zlib.h b/zlib.h index 14a925b..d85d7c2 100644 --- a/zlib.h +++ b/zlib.h @@ -1233,7 +1233,11 @@ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not