Menu

false positive shiftTooManyBits (and other ternary based on caller conditiions)

2023-01-16
2023-01-16
  • Daniel Black

    Daniel Black - 2023-01-16
    template <unsigned int width> class Bitmap
    {
      static const int BITS_PER_ELEMENT= sizeof(unsigned long long) * 8;
      static const int ARRAY_ELEMENTS= (width + BITS_PER_ELEMENT - 1) / BITS_PER_ELEMENT;
    
      unsigned long long buffer[ARRAY_ELEMENTS];
    
    private:
      unsigned long long bit_mask(unsigned int n) const
      {
        return ARRAY_ELEMENTS == 1 ? 1ULL << n : 1ULL << (n % BITS_PER_ELEMENT);
      }
    public:
      void intersect_and_pad()
      {
        if (ARRAY_ELEMENTS > 1 && (width % BITS_PER_ELEMENT))
          buffer[ARRAY_ELEMENTS - 1]= bit_mask(width) - 1;
      }
    };
    
    static Bitmap<64> c;
    
    /tmp/z.c++:11:39: error: Shifting 64-bit value by 64 bits is undefined behaviour [shiftTooManyBits]
        return ARRAY_ELEMENTS == 1 ? 1ULL << n : 1ULL << (n % BITS_PER_ELEMENT);
                                          ^
    /tmp/z.c++:17:44: note: Calling function 'bit_mask', 1st argument '64' value is 64
          buffer[ARRAY_ELEMENTS - 1]= bit_mask(width) - 1;
                                               ^
    /tmp/z.c++:11:39: note: Shift
        return ARRAY_ELEMENTS == 1 ? 1ULL << n : 1ULL << (n % BITS_PER_ELEMENT);
    

    The condition in intersect_and_pad of ARRAY_ELEMENTS > 1 excludes the true element of the ternary and hence the error.

     
  • CHR

    CHR - 2023-01-16

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

     

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.