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 can be an expression or the parenthesized name of a type. However, using the sizeof operator to determine the size of arrays is error prone.

...

Wiki Markup
In this noncompliant code example, the function {{clear()}} zeros the elements in an array. The function has one parameter declared as {{int array\[\]}} and is passed a static array consisting of 12 {{int}} as the argument. The function {{clear()}} uses the idiom {{sizeof(array) / sizeof(array\[0\])}} to determine the number of elements in the array.  However, {{array}} has a pointer type because it is a parameter. As a result, {{sizeof(array)}} is equal to the {{sizeof(int \*)}}. For example, on an architecture (such as IA-32) where the {{sizeof(int) == 4}} and the {{sizeof(int *) == 4}}, the expression {{sizeof(array) / sizeof(array\[0\])}} evaluates to 1, regardless of the length of the array passed, leaving the rest of the array unaffected.

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: ARR01-CPP. Do not apply the sizeof operator to a pointer when taking the size of an array

Bibliography

unmigrated-wiki-markup

\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.7.5.2, "Array declarators"

MITRE CWE: CWE-467, "Use of sizeof() on a Pointer Type"

Bibliography

Wiki Markup
 declarators"
\[[Drepper 2006|AA. Bibliography#Drepper 06]\] Section 2.1.1, "Respecting Memory Bounds"
\[[MITRE 2007|AA. Bibliography#MITRE 07]\] [CWE ID 467|http://cwe.mitre.org/data/definitions/467.html], "Use of sizeof() on a Pointer Type"

...

      06. Arrays (ARR)      ARR02-C. Explicitly specify array bounds, even if implicitly defined by an initializer