Versions Compared

Key

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

When performing pointer arithmetic, the size of the value to add or subtract to a pointer is automatically scaled to the size of the type of the pointed-to array object. Adding a value that is not unitless to a or subtracting an integer value which is scaled differently than the pointer shall be diagnosed (subject to exceptions below) because the behavior is undefined if both the pointer operand and the result do not point to elements of the same array object, or one past the last element of the array object.

this can result in undefined and unexpected behavior. For example, the sizeof operators operator and offsetof macro return a byte value with unit bytes, the function strlen()} returns a value that is unitless, and the function wcslen() returns a value that is unitless.

Wiki Markup
A common mistake is to add the size of an array to the array itself
(i.e. arr
 (that is, {{arr\[sizeof(arr)\]}} or {{arr + sizeof(arr))}}.  One correct idiom is to divide the size of the array by the size of the first element in the array, yielding a value that is unitless (i.e., {{arr\[sizeof(arr)/sizeof(arr[0])\])}}.

Noncompliant Code Example

In this noncompliant code example, the pointer buf is added to sizeof(buf), which is clearly incorrect . This is noncompliant because sizeof(buf) has unit bytes byte scale and buf is scaled to int.

Code Block
bgColor#FFCCCC
int buf[INTBUFSIZE];
int *buf_ptr = buf;

while (havedata && buf_ptr < (buf + sizeof(buf))) {
    *buf_ptr++ = parseint(getdata);
}

...