>
>
>
V102. Usage of non memsize type for poi…


V102. Usage of non memsize type for pointer arithmetic.

The analyzer found a possible error in pointer arithmetic. The error may be caused by an overflow during the determination of the expression.

Let's take up the first example.

short a16, b16, c16;
char *pointer;
...
pointer += a16 * b16 * c16;

The given example works correctly with pointers if the value of the expression "a16 * b16 * c16" does not excess 'INT_MAX' (2Gb). This code could always work correctly on the 32-bit platform because the program never allocated large-sized arrays. On the 64-bit platform the programmer using the previous code while working with an array of a large size would be disappointed. Suppose, we would like to shift the pointer value in 3000000000 bytes, and the variables 'a16', 'b16' and 'c16' have values 3000, 1000 and 1000 correspondingly. During the determination of the expression "a16 * b16 * c16" all the variables, according to the C++ rules, will be converted to type int, and only then the multiplication will take place. While multiplying an overflow will occur, and the result of this would be the number -1294967296. The incorrect expression result will be extended to type 'ptrdiff_t' and pointer determination will be launched. As a result, we'll face an abnormal program termination while trying to use the incorrect pointer.

To prevent such errors one should use memsize types. In our case it will be correct to change the types of the variables 'a16', 'b16', 'c16' or to use the explicit type conversion to type 'ptrdiff_t' as follows:

short a16, b16, c16;
char *pointer;
...
pointer += static_cast<ptrdiff_t>(a16) *
       static_cast<ptrdiff_t>(b16) *
       static_cast<ptrdiff_t>(c16)

It's worth mentioning that it is not always incorrect not to use memsize type in pointer arithmetic. Let's examine the following situation:

char ch;
short a16;
int *pointer;
...
int *decodePtr = pointer + ch * a16;

The analyzer does not show a message on it because it is correct. There are no determinations which may cause an overflow and the result of this expression will be always correct on the 32-bit platform as well as on the 64-bit platform.

Additional materials on this topic: