Main Content

MISRA C++:2023 Rule 8.7.1

Pointer arithmetic shall not form an invalid pointer

Since R2024b

Description

Rule Definition

Pointer arithmetic shall not form an invalid pointer.

Rationale

When performing pointer arithmetic on a pointer to an array element, the resulting points is invalid if it does not point to one of these:

  • An element of the same array

  • One past the last element of the same array

Dereferencing an invalid pointer results in undefined behavior. This rule applies to these arithmetic operations:

  • Binary +, -

  • +=, -=

  • Preincrement and postincrement

  • Predecrement and postdecrement

  • Indexing

Polyspace Implementation

Polyspace® reports a violation of this rule if any of these conditions is true:

  • Invalid pointer arithmetic operation — The result of pointer arithmetic on a pointer to an array element does not point to an element of the same array or one past the last element of the array.

  • Arithmetic operation on pointers to objects that are not arrays — You use pointer arithmetic on a nonarray type pointer, for example, using pointer arithmetic to traverse the fields of a structure.

  • Invalid argument for memory function — You use invalid arguments for a memory function such as memchr, memcmp, memcpy, memmove, memset, strncat, strncmp, strncpy, or strxfrm. For example, the memcpy function copies to an array that cannot accommodate the number of bytes copied.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

int foo(const int *a) {
	return *(a + 9); //Noncompliant
}

void bar() {
	int b[5];
	foo(b);

}

In this example, the pointer resulting from the operation (a + 9) points beyond one past the end of the array a. This pointer is invalid and dereferencing it is undefined behavior. Polyspace reports a violation of this rule.

#include <cstring>
char buf1[6] = "12345";
char buf2[11] = "1234567890";

void foo() {

	if(std::memcmp(buf1, buf2, 7) == 0)   // Noncompliant
	{
		//...
	}

}

In this example, the function std::memcmp compares the first seven characters in the arrays buf1 and buf2. Because buf1 contains five characters, this use of the std::memcmp function is invalid. Polyspace reports a violation of this rule.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2024b