Menu

false negative: uninitialized variable usage not detected in case variable set in for loop

Pieter D
2021-06-29
2021-06-30
  • Pieter D

    Pieter D - 2021-06-29

    Hi,

    I am not sure this is already tracked by a bug ticket.
    GCC and cppcheck do not detect that entries_bad_format is used as unitialized variable in case of for loops not being executed.
    Simplified code snippet:

    #include <stdio.h>
    #include <stdbool.h>
    int main()
    {
         bool entries_bad_format;
         unsigned int n_entries = 0; // In real example can be assigned by anything mostly > 0 but could be 0 (json_array_size)
    
        for (size_t i = 0; i < n_entries; i++)
        {
            entries_bad_format = true;
        }
        if(entries_bad_format)
            printf("hello");
         return 0;
    }
    

    gcc -Wall -Wextra test.c -o test
    cppcheck test.c --enable=all

    Checking test.c ...
    test.c:9:23: style: Checking if unsigned expression 'i' is less than zero. [unsignedLessThanZero]
     for (size_t i = 0; i < n_entries; i++)
                          ^
    test.c:7:28: note: Assignment 'n_entries=0', assigned value is 0
      unsigned int n_entries = 0;
                               ^
    test.c:9:23: note: Unsigned less than zero
     for (size_t i = 0; i < n_entries; i++)
    

    When modifying code to:

    #include <stdio.h>
    #include <stdbool.h>
    int main()
    {
         bool entries_bad_format;
        if(entries_bad_format)
            printf("hello");
         return 0;
    }
    

    GCC:
    test.c: In function ‘main’:
    test.c:9:4: warning: ‘entries_bad_format’ is used uninitialized in this function [-Wuninitialized]
    9 | if(entries_bad_format)
    | ^

    cppcheck:
    Checking test.c ...
    test.c:9:5: error: Uninitialized variable: entries_bad_format [uninitvar]
    if(entries_bad_format)
    ^

    Thank you for making cppcheck better every day!

    Kind regards,
    Pieter

     

    Last edit: Pieter D 2021-06-30
  • Daniel Marjamäki

    hmm it works for me from cppcheck-2.4. which version do you have?

     
  • Pieter D

    Pieter D - 2021-06-30

    Sorry for the inconvenience.
    Apparantly I was running it with 1.90, indeed on 2.4.1 this particular simplified case above is fixed. In our case the n_entries is filled in by size_t json_array_size(const json_t *array (jansson lib) and as cppcheck does not know that lib (no lib cfg yet) it fails to find it propably?

     

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.