Capturing overflow of left shift of constant 1 with compiler warning?

We write code inside the Linux kernel, so, anyway, I could not get PC-Lint / Flexelint to work with the Linux kernel code. Too many embedded characters, etc. But this is a side issue.

We have any number of compilers, starting with gcc, but also with others. Their warning options are becoming more powerful over time, and they are also pretty powerful tools for static analysis.

This is what I want to catch. Yes, I know that it breaks some things that are easy to catch in the code review, such as “no magic numbers” and “beware of bit offsets,” but this is only if you look at this section of the code. Anyway, here it is:

unsigned long long foo;
unsigned long bar;

[... lots of other code ...]

foo = ~(foo + (1<<bar));

Next, the description of the problem is UPDATED - even with a bar limited to 16, there is still a problem. To clarify, the problem is an implicit int-type constant, which unplannedly makes a complex expression violate the rule that all calculations are performed with the same size and signature.

Problem: "1" is not long, but, as a constant of small value, int is used by default. Therefore, even if the actual value of the bar never exceeds, say, 16, still the expression (1<<bar)will overflow and destroy the whole calculation.

Perhaps the right solution: write 1ULL instead.

Is there a known compiler and compiler warning flag that points to this (revised) problem?

+3
1

, . - , bar , ( ) int, . , , ( ).

Open Source URL- , , Linux .

+1

Source: https://habr.com/ru/post/1712806/


All Articles