Menu

Bound checking bug with unsigned long long

2021-01-07
2021-01-30
  • Trung Nguyen

    Trung Nguyen - 2021-01-07

    I'm testing cppcheck 2.3 with some code and there seems to be a bug with array bound checking for unsigned long long. In the snippet of code below, if variable i is unsigned int there is no error flagged by cppcheck but if i is unsigned long long, it spits out an error. Is this a known issue?

    #include <stdio.h>
    
    int main ()
    {
    
    //    unsigned int i = (unsigned int)~0;
        unsigned long long i = (unsigned long long)~0;
        int myArray[10];
    
        if (i > 9) return -1;
        myArray[i] = 0;
    }
    

    test.c:11:12: error: Array 'myArray[10]' accessed at index -1, which is out of bounds. [negativeIndex]
    myArray[i] = 0;
    ^
    test.c:7:28: note: Assignment 'i=(unsigned long long)~0', assigned value is -1
    unsigned long long i = (unsigned long long)~0;
    ^
    test.c:10:11: note: Assuming condition is false
    if (i > 9) return -1;
    ^
    test.c:11:12: note: Negative array index
    myArray[i] = 0;

    The error is also funny (i.e. negative index) since the variable is unsigned but it is out-of-bound access if you try to access 0xFFFFFFFFFFFFFFFF element.

     
  • CHR

    CHR - 2021-01-30

    I have a feeling that this problem is also related to https://trac.cppcheck.net/ticket/10150.
    cppcheck seems to treat uint64_t as a signed type. Assigning the literal 18446744073709551615 gives the same warning.

     

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.