Menu

Can we detect uninitialized local union variables

Daniel Su
2023-11-28
2023-11-28
  • Daniel Su

    Daniel Su - 2023-11-28

    (Cppcheck version : 2.10)

    Hi everyone,
    I would like to use Cppcheck to check if all the local union variable in my legacy projects are initialized, so that there won't be any garbage value in their memory address.

    Please refer to the demo code below. After running Cppcheck, there's no further error or warning in the line where I left a uninitialized, union type local variable on purpose. It seems that Cppcheck only shows the MISRA-C style warning "The union keyword should not be used" in the code section.

    Is it possiable to do such an analysis by using Cppcheck? Please give me some hints.
    Thanks for your time!

    typedef unsigned char UBYTE;
    typedef unsigned short UWORD;
    
    typedef union
    {
        UWORD  word;
        struct
        {       
            UBYTE Lbyte;
            UBYTE Hbyte;    
        }byte;
        struct
        {
            UWORD LBLbit4:4;
            UWORD LBHbit4:4;
            UWORD HBLbit4:4;
            UWORD HBHbit4:4;
        }bit4;
        struct
        {
             UWORD bit0:1;
             UWORD bit1:1;
             UWORD bit2:1;
             UWORD bit3:1;
             UWORD bit4:1;
             UWORD bit5:1;
             UWORD bit6:1;
             UWORD bit7:1;
             UWORD bit8:1;
             UWORD bit9:1;
             UWORD bit10:1;
             UWORD bit11:1;
             UWORD bit12:1;
             UWORD bit13:1;
             UWORD bit14:1;
             UWORD bit15:1;
    
        }bit;   
    }uuWORD;
    
    static UWORD UpdateBit12(UWORD flag)
    {
        uuWORD data; // uninitialized union variable
    
        if(flag == (UWORD)1)
        {
            data.bit.bit12 = 1;
        }
        else
        {
            data.bit.bit12 = 0;
        }
    
        return data.word;
    }
    
     
  • CHR

    CHR - 2023-11-28

    It seems that we bail out for unions, see https://trac.cppcheck.net/ticket/8046 and needsInitialization().

     

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.