0

I am compiling the below sample code but getting some warning messages. How to resolve these warning messages?

#include <iostream>
#include <cstdio>
#include <cstdint>

int main() 
{
  struct stRecord 
  {
    uint8_t SType;
    uint8_t TypeNo;
    uint8_t Length[2];
    uint8_t Address[8];
  };
  uint8_t payload_size = 37;
  size_t fw_remaining_size = 80;

  if ((payload_size + 1U) * 2 > fw_remaining_size - sizeof(stRecord)) 
  {
  }
  return 0;
}

if ((payload_size + 1U) * 2 > fw_remaining_size - sizeof(stRecord))

At the above line, getting below warning messages:

C26451: Arithmetic overflow: Using operator '*' on a 4 byte value and then casting the result to a 8 byte value.
Cast the value to the wider type before calling operator '*' to avoid overflow (io.2).

C26451: Arithmetic overflow: Using operator '+' on a 4 byte value and then casting the result to a 8 byte value.
Cast the value to the wider type before calling operator '+' to avoid overflow (io.2).

I am trying to avoid the (static_cast<size_t>(payload_size)

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
prakash
  • 49
  • 8
  • Change the type of `payload_size`: `size_t payload_size = 37;`. – Adrian Mole Oct 26 '22 at 07:19
  • I didn't get the warning when I tried compiling, so I'm left to guess. By any chance, does changing `1U` to `1ULL` change the warning? – JaMiT Oct 26 '22 at 07:26
  • The warning is BS. There is no casting anywhere. – n. m. could be an AI Oct 26 '22 at 07:30
  • Hi @AdrianMole, I can't change payload_size from "uint8_t" to "size_t". Because after that I am assigning payload_size to other variables of type "uint8_t" and "uint32_t" – prakash Oct 26 '22 at 08:32
  • Hi @JaMiT, I have changed 1U to 1ULL. With that the warning is resolved. But i am not sure whether can i use "IULL" or not. – prakash Oct 26 '22 at 08:34
  • @prakash Why would you not be able to use `1ULL`? It's been part of the language since C++11. In any event, the left side of your inequality is computed as an `unsigned` (4 bytes), while the right side is computed as an `unsigned long long` (8 bytes). Making these match gets rid of the warning (see the duplicate I'm about to propose). Ways to make the left side 8 bytes include 1) changing the type of `payload_size`, 2) changing the type of `1U`, and 3) `static_cast`. (Changing the type of the `2` would probably eliminate only one of the warnings.) Be wary of eliminating all possibilities. – JaMiT Oct 27 '22 at 00:17

0 Answers0