Menu

doubleFree false-positive on fdopen(3)

2024-05-26
2024-05-27
  • Christian Göttsche

    The following snipped causes a doubleFree false positive, since fdopen(3) is treated to always deallocate a file descriptor resource, and not only on success:

    #include <fcntl.h>
    #include <stdio.h>
    #include <unistd.h>
    
    void foo(void) {
        int fd;
        FILE *stream;
    
        fd = open("/foo", O_RDONLY);
        if (fd == -1)
            return;
    
        stream = fdopen(fd, "r");
        if (!stream) {
            close(fd);
            return;
        }
    
        fclose(stream);
    }
    

    Report:

    cppcheck_fp.c:15:3: error: Resource handle 'fd' freed twice. [doubleFree]
      close(fd);
      ^
    cppcheck_fp.c:13:11: note: Resource handle 'fd' freed twice.
     stream = fdopen(fd, "r");
              ^
    cppcheck_fp.c:15:3: note: Resource handle 'fd' freed twice.
      close(fd);
      ^
    

    fdopen(3) only transforms the given file descriptor to a stream on success, not on failure.
    Same also applies to fdopendir(3), but this functions is currently not registered as deallocator for file descriptor resources.

     
  • CHR

    CHR - 2024-05-27

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/12781

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.