http://gcc.gnu.org/bugzilla/show_bug.cgi?id=54085

             Bug #: 54085
           Summary: free storage leak when fdopen is combined with close
                    of the file descriptor
    Classification: Unclassified
           Product: gcc
           Version: 3.4.4
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
        AssignedTo: unassig...@gcc.gnu.org
        ReportedBy: mnew...@dragonnorth.com


// I ran across a problem that manifest itself as a free storage leak.
//
// We open a file using open so we can set attributes. We then
// convert the file descriptor to a file handle with fdopen in order to 
// use the fflush function to ensure output has completed. We then closed the
file
// with the close function. Some memory allocated with the fdopen does not get
// released in this sequence. Putting this in a loop gradually uses up all
available
// memory as reported by the malloc_stats call.
//
// A greatly simplified testFunction that performs the critical tasks
// is provided below. Call this function in an infinite loop. Each time it is
// called it allocates memory which is never freed.
//
// Two scenarios are reasonable:
//
// BEST CASE
// The file descriptor and the file handle represent the same entity
// and closing either releases all storage. After calling either close or
fclose
// calling fputc or write is incorrect. Calling close or fclose after
// either close is incorrect.
//
// SUFFICIENT SOLUTION
// The file descriptor and file handle are independent and closing one
// does not effect the other. Closing the handle derived from the
// descriptor with fclose should not prevent a close of the handle with
// close. It is OK to ignore a write to the descriptor after an fclose.
// It is not OK to crash when an operation (write, close) is done after
// the fclose.
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

void testFunction(void) {
    FILE *pFile;
    int uartFD;

    uartFD = open("/dev/uart1",(O_RDWR | O_NONBLOCK));
    if (uartFD < 0) {
        return;
    };
    pFile = fdopen(uartFD,"w+");
    if (pFile != NULL) {
        fflush(pFile);
        // fclose(pFile); using this close fixes the problem BUT
        // you must also remove the close of the file descriptor
        close(uartFD);
    };
    return;
}

main () {
    while (1) testFunction();
}

Reply via email to