Menu

False positive for rule arrayIndexOutOfBoundsCond in cppcheck 2.9

2023-02-23
2023-02-23
  • Mark Spencer

    Mark Spencer - 2023-02-23

    Hello and thank you for producing such a fantastic open source product! I have, however, discovered the following issue. Consider the following snippet:

    #define XFD_MAX_CARDS 16
    typedef struct {
        int *cards[XFD_MAX_CARDS];
    } xfd_gauge_carddeck;
    
    int iterate_cards(xfd_gauge_carddeck *carddeck, int all, int sticky)
    {
        int ret = 0;
        /* Note: Does not generate false positive if you put XFD_MAX_CARDS in place of (sizeof(carddeck->cards)/sizeof(carddeck->cards[0])) */
        if (!all && (sticky > -1) && (sticky < (sizeof(carddeck->cards)/sizeof(carddeck->cards[0])))) {
            if (carddeck->cards[sticky])
                printf("value is %d\n", *carddeck->cards[sticky]);
        }
    
        return ret;
    }
    

    The above snippet kicks out an arrayIndexOutOfBoundsCond in cppcheck 2.9. Notably, using XFD_MAX_CARDS in place of the sizeof() math to generate the top end value clears the error.

     
  • Mark Spencer

    Mark Spencer - 2023-02-23

    For clarity, please see the following command line and results

    [xfs]$ cppcheck --enable=all test.c
    Checking test.c ...
    test.c:11:22: warning: Either the condition 'sticky>-1' is redundant or the array 'carddeck->cards[16]' is accessed at index 16, which is out of bounds. [arrayIndexOutOfBoundsCond]
      if (carddeck->cards[sticky])
                         ^
    test.c:10:22: note: Assuming that condition 'sticky>-1' is not redundant
     if (!all && (sticky > -1) && (sticky < (sizeof(carddeck->cards)/sizeof(carddeck->cards[0])))) {
                         ^
    test.c:11:22: note: Array index out of bounds
      if (carddeck->cards[sticky])
                         ^
    test.c:6:0: style: The function 'iterate_cards' is never used. [unusedFunction]
    
    ^
    [xfs]$ 
    
     
  • CHR

    CHR - 2023-02-23

    No repro with head, so maybe this is already fixed.

     

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.