Menu

False Uninitialized variable

2024-05-13
2024-05-14
  • Martin Poupě

    Martin Poupě - 2024-05-13

    Hello,
    have a code:

    #include <stdint.h>
    
    static uint8_t GetValue(uint8_t n)
    {
        uint8_t i,buf[10];
        for(i = 0; i < n; i++)
        {
            buf[i] = i;
        }
        return buf[n / 2];
    }
    
    uint8_t Test(uint8_t k)
    {
        return GetValue((k & 7) + 1);
    }
    

    cppcheck 2.14 says:
    tmp.c:10:12: warning: Uninitialized variable: buf [uninitvar]
    return buf[n / 2];
    ^
    tmp.c:6:18: note: Assuming condition is false
    for(i = 0; i < n; i++)
    ^
    tmp.c:10:12: note: Uninitialized variable: buf
    return buf[n / 2];
    ^
    However n is always at least 1, so the used part of the buf is always set.
    I know, it requires global analysis :-)

     
  • CHR

    CHR - 2024-05-13

    So GetValue() must not be called with n == 0, which is dangerous at best.
    We also warn for

    int f(int i) {
        int a;
        if (i != 42)
            a = 7;
        return a;
    }
    
     
    • Martin Poupě

      Martin Poupě - 2024-05-14

      Yes, it is dangerous to call GetValue(0), however this case will never happen. The function is static, so not callable from outside of this source and the only place of call is safe, because routine Test() always calls with n at least 1.

       

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.