Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Bitwise operators include the complement operator ~, bitwise shift operators >> and <<, bitwise AND operator &, bitwise exclusive OR operator ^, and bitwise inclusive OR operator |. Bitwise operators should be used only with unsigned integer operands, as the results of some bitwise operations on signed integers are implementation-defined.

Noncompliant Code Example (Right Shift)

The right-shift operation may be implemented as either an arithmetic (signed) shift or a logical (unsigned) shift. If E1 in the expression E1 >> E2 has a signed type and a negative value, the resulting value is implementation-defined. Also, a bitwise shift can result in undefined behavior. (See INT34-C. Do not shift a negative number of bits or more bits than exist in the operand.)

This noncompliant code example can result in an error condition on implementations in which an arithmetic shift is performed, and the sign bit is propagated as the number is shifted [Dowd 2006].

Code Block
bgColor#FFcccc
langc
int rc = 0;
int stringify = 0x80000000;
char buf[sizeof("256")];
rc = snprintf(buf, sizeof(buf), "%u", stringify >> 24);
if (rc == -1 || rc >= sizeof(buf)) {
  /* handle error */
}

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V

50 S
120 S
331 S

Fully implemented.

Fortify SCA

V. 5.0

 

Can detect violations of this recommendation with the CERT C Rule Pack.

Splint

Include Page
Splint_V
Splint_V

 

 

Compass/ROSE

 

 

Can detect violations of this rule. In particular, it flags bitwise operations that involved variables not declared with unsigned type.

PRQA QA-C
Include Page
PRQA_V
PRQA_V

0502

4130 .

4131

 

Fully implemented

Related Vulnerabilities

...

CERT C++ Secure Coding Standard: INT13-CPP. Use bitwise operators only on unsigned operands

ISO/IEC 2003 Section 6.5.7, "Bitwise shift operators"

ISO/IEC 9899:2011 Section 6.5.7, "Bitwise shift operators"

ISO/IEC TR 24772 "STR Bit representations," "XYY Wrap-around error," and "XZI Sign extension error"

MITRE CWE: CWE-682, "Incorrect calculation"

Bibliography

[Dowd 2006] Chapter 6, "C Language Issues"

...