Menu

[constVariablePointer] and pointer arithmetic

2023-07-07
2023-07-07
  • Martin Poupě

    Martin Poupě - 2023-07-07

    Hello,
    cppcheck 2.11 suggests to use const pointer, where in reality the pointer cannot be const.
    Have a program:

    typedef struct
    {
        int i;
    }STRUC1;
    
    typedef struct
    {
        STRUC1 items[4]; 
        unsigned current;
    }STRUC2;
    
    STRUC2 *GetStruc2(void);
    int GetValue(void);
    void modify()
    {
        STRUC2 *p = GetStruc2();
        if(p && p->current)
        {
            STRUC1 *target = p->items + p->current;
            target->i = GetValue();
        }
    }
    

    cppcheck 2.10 does not report this, so I cannot use your online demo.

    cppcheck 2.11 on my project says: style: Variable 'p' can be declared as pointer to const [constVariablePointer] STRUC2 *p = GetStruc2();

    However making "p" const will force "target" be const, so the assignment will fail.
    Simple change from:
    STRUC1 *target = p->items + p->current;
    to:
    STRUC1 *target = &p->items[p->current];
    will dismiss the warning from cppcheck.

    Best Regards Martin

     
  • CHR

    CHR - 2023-07-07

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

     

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.