Search code examples
cprefast

Prefast Warning:"Arithmetic Overflow: 32-bit value is shifted, then cast to 64-bit value."


I have declared macros like this:

#define F_MASK_4_BIT 0xF
#define GET_F_4BIT_MASK(F, P) (((F) & (F_MASK_4_BIT << (P * 4))) >> (4 * P))

using macro like this:

uint8_t Feature = GET_F_4BIT_MASK(E, P);

Where E is uint64_t datatype P is uint8_t datatype

Which gives warning by Prefast: C6297: Arithmetic overflow: 32-bit value is shifted, then cast to 64-bit value. Results might not be an expected value.

How to fix this?


Solution

  • It's pretty self-explaining. If P has any value larger than 7 (7*4=28, max is 31), the F_MASK_4_BIT << (P * 4) will overflow. Because F_MASK_4_BIT is a integer constant of type int.

    Fix this by using an appropriate type for the integer constant:

    #define F_MASK_4_BIT 0xFull