From: Mark Adler Date: Thu, 20 Oct 2011 16:07:58 +0000 (-0700) Subject: Add comment to gzdopen() in zlib.h to use dup() when using fileno(). X-Git-Tag: v1.2.5.2~21 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6dbf1d10263dbf2f49d12d788f89ab308ba4ca6d;p=thirdparty%2Fzlib-ng.git 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. --- diff --git a/zlib.h b/zlib.h index 14a925bfb..d85d7c29e 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