Versions Compared

Key

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

...

In this noncompliant code example, a pointer is set to reference the start of an array. Array elements are accessed sequentially within the for loop. The array pointer ip is incremented on each iteration.

Code Block
bgColor#ffcccc
langcpp
int ar[20];

for (int *ip = &ar[0]; ip < &ar[21]; ip++) {
  *ip = 0;
}

...

Wiki Markup
This compliant solution fixes the problem from the previous noncompliant code example by using the common idiom {{sizeof(ar)/sizeof(ar\[0\])}} to determine the actual number of elements in the array.  This idiom works only when the definition of the array is visible (see [ARR01-CPP. Do not apply the sizeof operator to a pointer when taking the size of an array]).

Code Block
bgColor#ccccff
langcpp
int ar[20];

for (int *ip = &ar[0]; ip < &ar[sizeof(ar)/sizeof(ar[0])]; ip++) {
  *ip = 0;
}

...

In this noncompliant code example, an iterator is set to reference the beginning of a vector. Vector elements are accessed sequentially within the for loop. The iterator ip is incremented on each iteration.

Code Block
bgColor#ffcccc
langcpp
vector<int> ar( 20, 0);
vector<int>::iterator ip = ar.begin();
for (int i = 1; i <= 22; i++) {
  *ip++ = 1;
}

...

This compliant solution fixes the problem from the previous noncompliant code example by using the ranges ar.begin() and ar.end() to determine how many iterations should be executed.

Code Block
bgColor#ccccff
langcpp
vector<int> ar( 20, 0);
for (vector<int>::iterator ip = ar.begin(); ip < ar.end(); ip++) {
  *ip++ = 1;
}

...

In this noncompliant code example, the programmer is trying to determine if a pointer added to a length will wrap around the end of memory.

Code Block
bgColor#ffcccc
langcpp
char *buf;
size_t len = 1 << 30;

/* Check for overflow */
if (buf + len < buf) {
  len = -(size_t)buf-1;
}

...

In this compliant solution, both references to buf are cast to size_t. Because {[size_t}} is an unsigned type, C++2003 guarantees that it has modulo behavior.

Code Block
bgColor#ccccff
langcpp
char *buf;
size_t len = 1 << 30;

/* Check for overflow */
if ((size_t)buf+len < (size_t)buf) {
  len = -(size_t)buf-1;
}

...

Another interesting case is shown in this noncompliant code example. The expression buf + n may wrap for large values of n, resulting in undefined behavior.

Code Block
bgColor#ffcccc
langcpp
int process_array(char *buf, size_t n) {
  return buf + n < buf + 100;
}

...

In this compliant solution, the "optimization" is performed by hand.

Code Block
bgColor#ccccff
langcpp
int process_array(char *buf, size_t n) {
  return n < 100;
}

...