Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

...

Noncompliant Code Example

Wiki MarkupIn 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.

Code Block
bgColor#FFcccc
langc
void clear(int array[]) {
  for (size_t i = 0; i < sizeof(array) / sizeof(array[0]); ++i) {
     array[i] = 0;
   }
}

void dowork(void) {
  int dis[12];

  clear(dis);
  /* ... */
}

Wiki MarkupThe footnote in Section 6.5.3.4 of the C Standard \[ [ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999] \] explains this:

When applied to a parameter declared to have array or function type, the sizeof operator yields the size of the adjusted (pointer) type . . . .

...

Code Block
bgColor#ccccff
langc
void clear(int array[], size_t len) {
    for (size_t i = 0; i < len; i++) {
     array[i] = 0;
  }
}

void dowork(void) {
  int dis[12];

  clear(dis, sizeof(dis) / sizeof(dis[0]));
  /* ... */
}

Wiki MarkupThis {{sizeof(array) / sizeof(array\[0\])}} idiom will succeed provided the original definition of {{array}} is visible.

Noncompliant Code Example

...

Tool

Version

Checker

Description

Section

Splint

Include Page
c:Splint_Vc:
Splint_V

 

 

Section

Compass/ROSE

 

 

Section

can detect violations of the recommendation, but it cannot distinguish between incomplete array declarations and pointer declarations

Section

LDRA tool suite

Include Page
c:LDRA_Vc:
LDRA_V
Section

401 S

Section

Partially Implemented

...

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

Bibliography

...

\[[Drepper 2006|AA. Bibliography#Drepper 06]\] Section 2.1.1, "Respecting Memory Bounds"

...

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