Menu

At a loss with a bounds checking message

2022-04-13
2022-04-13
  • Jens Nissen

    Jens Nissen - 2022-04-13

    The code below gives exactly the error message which I wanted to prevent with my code.
    I don't understand why the check is redundant and I also don't understand, how the access can be out ouf of bounds.
    What's wrong here?

    [cpptest.c:14] (warning) Either the condition 'index>=0' is redundant or the array 'board_info[4]' is accessed at index 4, which is out of bounds. [arrayIndexOutOfBoundsCond]

    #define NUM_ELEMENTS(arr) (sizeof (struct {int not_an_array:((void*)&(arr) == &((arr)[0]));}) * 0 + sizeof (arr) / sizeof (*(arr)))
    
    typedef struct 
    {
        int error;
    } BOARD_INFO;
    
    BOARD_INFO board_info[4];
    
    void clear_error(int index)
    {
        if ((index >= 0) && (index < NUM_ELEMENTS(board_info)))
        {
             board_info[index].error = 0;
        }
    }
    
    void main()
    {
        volatile int n = *(int*)0xF000;
        clear_error(n);
    }
    
     
  • CHR

    CHR - 2022-04-13

    Thanks for reporting, I have created a ticket: https://trac.cppcheck.net/ticket/10979
    How does that sizeof trick work, is it defining a bitfield?

     
  • Jens Nissen

    Jens Nissen - 2022-04-13

    The sizeof-thingy just avoids, that a non-array type is passed into the macro. It's a commonly used technique, not my idea. It will indeed create a compiler error like:

    bit-field 'not_an_array' width not an integer constant

     
  • Jens Nissen

    Jens Nissen - 2022-04-13

    The sizeof-thingy just avoids, that a non-array type is passed into the macro. It's a commonly used technique, not my idea. It will indeed create a compiler error like:

    bit-field 'not_an_array' width not an integer constant

     

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.