Versions Compared

Key

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

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. When the type of the operand is a variable - length array type (VLA) the expression is evaluated; otherwise, the operand is not evaluated.

When part of the operand of the sizeof operator is a VLA type and when changing the value of the VLA's size expression would not affect the result of the operator, it is unspecified whether or not the size expression is evaluated. See unspecified behavior 21 in section 22 in Annex J (Section J.1 of C99) of the C standard [ISO/IEC 9899:2011].

Providing an expression that appears to produce side effects may be misleading to programmers who are not aware that these expressions are not evaluated in the non-VLA case and has have unspecified results otherwise. As a result, programmers may make invalid assumptions about program state, leading to errors and possible software vulnerabilities.

...

In this noncompliant code example, the expression a++ is not evaluated, and the side effects in the expression are not executed.

Code Block
bgColor#FFcccc
langc

int a = 14;
int b = sizeof(a++);

...

This example compiles cleanly under Microsoft Visual Studio 2005, Version 8.0, with the /W4 option.

...

Code Block
bgColor#ccccff
langc

int a = 14;
int b = sizeof(a);
a++;

...

In the following noncompliant code example, the expression ++n in the initialization expression of a must be evaluated since evaluated because its value affects the size of the variable length array the VLA operand of the sizeof operator. However, since the expression ++n % 1 evaluates to 0, regardless of the value of n, its value does not affect the result of the sizeof operator. Consequently, and, thus, it is unspecified whether or not n is incremented or not.

Code Block
bgColor#FFcccc
langc

void f(size_t n) {
  size_t a = sizeof(int [++n]);           /* n must be incremented */
  size_t b = sizeof(int [++n % 1 + 1]);   /* n need not be incremented */
  /* ... */
}

...

Compliant Solution (Variable Length Array)

The This compliant solution below avoids changing the value of the variable n used in the sizeof expression and instead increments it safely outside of it.

Code Block
bgColor#ccccFF
langc

void f(size_t n) {
  size_t a = sizeof(int [n + 1]);
  ++n;

  size_t b = sizeof(int [n % 1 + 1]);
  ++n;
  /* ... */
}

...

LDRA tool suite

Tool

Version

Checker

Description

Section
Include Page
LDRA_V
LDRA_V
section

54 S

section

Fully

Implemented section

implemented

Compass/ROSE

 

 

 

Related Vulnerabilities

...

CERT C++ Secure Coding Standard: EXP06-CPP. Operands to the sizeof operator should not contain side effects

ISO/IEC 9899:19992011 Section 6.5.3.4, "The sizeof operator and _Alignof operators"

Bibliography

...