Menu

False positive: Uninitialized variable

2023-09-28
2023-10-02
  • Dotan Barak

    Dotan Barak - 2023-09-28

    Cppcheck 2.10 emits the following (false?) errors on the following code:
    main.c:16:19: error: Uninitialized variable: file [uninitvar]
    if (fseek(file, 0, SEEK_END) != 0) {

    It is worth mentioning, that when i added "#define EXAMPLE_MACRO" to the beginning of the code, everything was ok.

    #include <stdio.h>
    
    int main()
    {
            FILE *file;
    
    #ifdef EXAMPLE_MACRO
            file = fopen("/tmp/example.txt", "rb");
            if (file == NULL)
                    return 1;
    #else
            return 2;
    #endif
    
            if (fseek(file, 0, SEEK_END) != 0) {
                    fclose(file);
                    return 1;
            }
    
            fclose(file);
    
            return 0;
    }
    

    Thanks!

     
  • CHR

    CHR - 2023-09-28

    I have added your example to https://trac.cppcheck.net/ticket/8568
    Can you extend the ifdef to cover all of the conditional code?

     
  • Dotan Barak

    Dotan Barak - 2023-09-28

    Do you mean?
    For this code, i still see an error:

    /tmp/main.c:21:9: error: Uninitialized variable: file [uninitvar]
    fclose(file);

    #include <stdio.h>
    
    int main()
    {
            FILE *file;
    
    #ifdef EXAMPLE_MACRO
            file = fopen("/tmp/example.txt", "rb");
            if (file == NULL)
                    return 1;
    
            if (fseek(file, 0, SEEK_END) != 0) {
                    fclose(file);
                    return 1;
            }
    
    #else
            return 2;
    #endif
    
            fclose(file);
    
            return 0;
    }
    
     
  • CHR

    CHR - 2023-09-28
    #include <stdio.h>
    
    int main()
    {
    #ifdef EXAMPLE_MACRO
            FILE *file;
            file = fopen("/tmp/example.txt", "rb");
            if (file == NULL)
                    return 1;
    
            if (fseek(file, 0, SEEK_END) != 0) {
                    fclose(file);
                    return 1;
            }
    
            fclose(file);
    
            return 0;
    #else
            return 2;
    #endif
    }
    
     
  • Dotan Barak

    Dotan Barak - 2023-10-02

    Understood, thanks

     

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.