Versions Compared

Key

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

...

Wiki Markup
In this non-compliant 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 twelve {{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 {{sizeof(int \*)}}.  For example, in GCC on IA32IA-32, 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
void clear(int array[]) {
  size_t i;
  for (i = 0; i < sizeof (array) / sizeof (array[0]); ++i) {
     array[i] = 0;
   }
}
/* ... */
int dis[12];

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

...

Code Block
bgColor#ccccff
void clear(int array[], size_t size) {
  size_t i;
  for (i = 0; i < size; i++) {
     array[i] = 0;
  }
}
/* ... */
int dis[12];

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

Risk Assessment

...

The LDRA tool suite V 7.6.0 is able to detect violations of this recommendation.

The tool Compass Rose can detect violations of the recommendation, but it cannot distinguish between incomplete array declarations and pointer declarations.

...