Menu

[internalAstError] when assigning a compound literal with designators and array access

2020-12-28
2021-02-11
  • Bento Borges Schirmer

    Hello

    Cppcheck (version 2.3) have been serving me really well, but yesterday I came across to an internalAstError.
    The following C code assigns to a the fifth element on an array initialized using a compound literal and designators to initialize its elements.

    int main(void)
    {
            int a = (int[]){[4] = 1}[4];
            return (a);
    }
    

    Although it compiles and runs fine using GCC, Clang and TCC without warnings (-Wpedantic -Wall -Wextra), running the bellow gives the following output:

    $ cppcheck --debug assignment-of-designated-initialized-compound-literal.c
    Checking assignment-of-designated-initialized-compound-literal.c ...
    assignment-of-designated-initialized-compound-literal.c:3:8: error: Syntax Error: AST broken, binary operator '=' doesn't have two operands. [internalAstError]
     int a = (int[]){[4] = 1}[4];
           ^
    

    However, this seems to run fine:

    int main(void)
    {
            int *a = (int[]){[4] = 1};
    
            return (a[4]);
    }
    

    Or this, but this one raises [unusedFunction] when run with --enable=all:

    static int function(int a)
    {
            return (a);
    }
    
    int main(void)
    {
            int a = function((int[]){[4] = 1}[4]);
    
            return (a);
    }
    

    I saw on Trac this issue, but I dunno if it is related: https://trac.cppcheck.net/ticket/9513

    Thanks in advance!

     

    Last edit: Bento Borges Schirmer 2020-12-28
  • CHR

    CHR - 2021-02-08

    Adding parentheses around the cast also avoids the warnings:

    int main1()
    {
            int a = ((int[]){[4] = 1})[4];
            return a;
    }
    
    int f(int a)
    {
            return a;
    }
    
    int main2()
    {
            int a = f( ((int[]){[4] = 1})[4] );
    
            return a;
    }
    

    Looking at the value flow (as far as I understand it), it seems that cppcheck doesn't quite parse this expression correctly though.
    (Added missing parentheses.)

     

    Last edit: CHR 2021-02-09
  • CHR

    CHR - 2021-02-11
     

Log in to post a comment.

MongoDB Logo MongoDB