Home > Blockchain >  Arithmetic overflow warning
Arithmetic overflow warning

Time:01-19

I have the following bit of code (nsections is defined as an int):

pipe_def.p_atamb     = new double[pipe_def.nsections 1];

I get this warning:

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).

What type should x be in new double array(x)int or int64? (I thought int.)

CodePudding user response:

What type should x be in new double[x] ? int or int64? I thought int.

It should be (or will anyway be converted to) std::size_t.

  • cppreference

    If type is an array type, all dimensions other than the first must be specified as ... type std::size_t (since C 14) ... [or] ... any expression convertible to std::size_t (since C 14)

  • Standard: [expr.new]/8

    If the expression in a noptr-new-declarator is present, it is implicitly converted to std​::​size_­t.

CodePudding user response:

The count (dimension) argument for the new[] operator is of size_t type, not int. On your platform (which appears to be MSVC, targeting 64-bit architecture), that size_t type is an unsigned long long (8 bytes). Hence the warning.

You can silence this warning by casting either of the operands of the addition:

pipe_def.p_atamb = new double[static_cast<size_t>(pipe_def.nsections)   1];

Or, if you are compiling to the C 23 Standard, you can use the integer literal suffix for the size_t type on the constant:

pipe_def.p_atamb = new double[pipe_def.nsections   1zU];

(Prior to C 23, you could use the uLL suffix but that will become platform-dependent, because the size_t type for 32-bit builds is only a 4-byte unsigned long.)

  • Related