Versions Compared

Key

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

...

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);
  /* ... */
}

Footnote 103 in section subclause 6.5.3.4 of the C Standard [ISO/IEC 9899:2011] explains:

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#FFcccc
langc
enum {ARR_LEN = 100};

void clear(int a[ARR_LEN]) {
  memset(a, 0, sizeof(a)); /* errorError */
}

int main(void) {
  int b[ARR_LEN];
  clear(b);
  assert(b[ARR_LEN / 2]==0); /* mayMay fail */
  return 0;
}

Compliant Solution

...

Code Block
bgColor#ccccff
langc
enum {ARR_LEN = 100};

void clear(int a[], size_t len) {
  memset(a, 0, len * sizeof(int));
}

int main(void) {
  int b[ARR_LEN];
  clear(b, ARR_LEN);
  assert(b[ARR_LEN / 2]==0); /* cannotCannot fail */
  return 0;
}

Risk Assessment

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

Can detect violations of the recommendation but cannot distinguish between incomplete array declarations and pointer declarations

LDRA tool suite

Include Page
LDRA_V
LDRA_V

401 S

Partially implemented

Splint

Include Page
Splint_V
Splint_V

 

 

...

CERT C++ Secure Coding StandardARR01-CPP. Do not apply the sizeof operator to a pointer when taking the size of an array
MITRE CWECWE-467, Use of sizeof() on a pointer type
ISO/IEC TS 17961 (Draft)Taking the size of a pointer to determine the size of the pointed-to type [sizeofptr]

...

[Drepper 2006]Section 2.1.1, "Respecting Memory Bounds"
[ISO/IEC 9899:2011]Section Subclause 6.5.3.4, "The sizeof and _Alignof Operators"

...