Menu

Wrong calculation of sizeof dereference of a 2D array in struct

Ricozero
2023-10-27
2023-10-27
  • Ricozero

    Ricozero - 2023-10-27

    cppcheck version: 2.12.0

    Hi, I've been using cppcheck in our project, and found that when calculating sizeof dereference of a 2D array in struct, cppcheck may get a wrong answer.

    I reproduced this bug in the following code:

    #include <iostream>
    using namespace std;
    
    struct
    {
        int prop[10][30];
        int prop1d[10];
    }config;
    
    int prop[10][30];
    
    void fun()
    {
        // Case 1: sizeof dereference of a 2D array in struct
        // Result: CWE: 788
        // Array 'config.prop[10][30]' accessed at index config.prop[299][0], which is out of bounds.
        int num = sizeof(config.prop) / sizeof(*config.prop);
        cout << num << endl;
        for (int i = 0; i < num; ++i)
            cout << config.prop[i][0];
        cout << endl;
    
        // Case 2: sizeof [0] of a 2D array in struct
        // Result: cppcheck no error
        int num2 = sizeof(config.prop) / sizeof(config.prop[0]);
        cout << num2 << endl;
        for (int i = 0; i < num2; ++i)
            cout << config.prop[i][0];
        cout << endl;
    
        // Case 3: sizeof dereference of a 2D array
        // Result: cppcheck no error
        int num3 = sizeof(prop) / sizeof(*prop);
        cout << num3 << endl;
        for (int i = 0; i < num3; ++i)
            cout << prop[i][0];
        cout << endl;
    
        // Case 4: sizeof dereference of a 1D array in struct
        // Result: cppcheck no error
        int num4 = sizeof(config.prop1d) / sizeof(*config.prop1d);
        cout << num4 << endl;
        for (int i = 0; i < num4; ++i)
            cout << config.prop1d[i];
        cout << endl;
    }
    
    int main()
    {
        fun();
    }
    

    The logic and execution results of the 4 cases are the same, while cppcheck only reports an error on case 1, so I think this might be a bug of cppcheck.

    Simply switching to case 2 can suppress this error, but I think it's better to also post it here.

    Nevertheless, cppcheck has helped us a lot, thank you for your great work!

     

    Last edit: Ricozero 2023-10-27
  • CHR

    CHR - 2023-10-27

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/12126

     

    Last edit: CHR 2023-10-27

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.