Menu

cppcheck 2.5: false positive in the return value of a function

vix
2021-09-15
2021-09-17
  • vix

    vix - 2021-09-15
    #define hiword(x)   ((unsigned short)((x) >> 16))
    #define loword(x)   ((unsigned short)(x))
    
    typedef struct {
      unsigned short  f;
      unsigned short  s;
    } MyStruct;
    
    MyStruct foo(double v)
    {
       MyStruct retval={0};
       float u = (float)v;
    
       retval.f  = hiword(*(unsigned int *)&u);
       retval.s = loword(*(unsigned int *)&u);
    
       return(retval);
    }
    

    cppcheck gives
    CWE: 562
    Returning object that points to local variable 'u' that will be invalid when returning.
    on the line
    retval.s = loword(*(unsigned int *)&u);

    But, if I'm right, the address of u is dereferenced and so its value is returned into retval.

     
  • CHR

    CHR - 2021-09-15

    Which version do you use, and how do you call cppcheck? With current head, I get

    thud.c:14:16: portability: Casting from float * to unsigned int * is not portable due to different binary data representations on different platforms. [invalidPointerCast]
       retval.f  = hiword(*(unsigned int *)&u);
                   ^
    thud.c:15:15: portability: Casting from float * to unsigned int * is not portable due to different binary data representations on different platforms. [invalidPointerCast]
       retval.s = loword(*(unsigned int *)&u);
                  ^
    

    but not the warning you describe.

     
  • vix

    vix - 2021-09-15

    I use cppcheck 2.5 from the GUI and I select Analyze >> Folder pointing to the folder with all my source files (.c and .h).
    I get the same result if I copy and paste the code snippet into an empty file.c and select Analyze >> File.

    I set the C standard to C99

    I find the same warning as you, but moreover I get CWE: 562 as an error (not a warning).

     

    Last edit: vix 2021-09-15
  • CHR

    CHR - 2021-09-15

    Ok, I can reproduce it with 2.5. You can either use a current build, or wait for 2.6.

     
  • Martin Brieg

    Martin Brieg - 2021-09-17

    -- sorry, wrong thread --

     

    Last edit: Martin Brieg 2021-09-17

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.