MISRA C:2023 Rule 18.4
The +, -, += and -= operators should not be applied to an expression of pointer type
Since R2024a
Description
Rule Definition
The +, -, += and -= operators should not be applied to an expression of pointer type.
Rationale
The preferred form of pointer arithmetic is using the array
subscript syntax ptr[expr]
. This syntax is clear
and less prone to error than pointer manipulation. With pointer manipulation,
any explicitly calculated pointer value has the potential to access
unintended or invalid memory addresses. Array indexing can also access
unintended or invalid memory, but it is easier to review.
To a new C programmer, the expression ptr+1
can be mistakenly
interpreted as one plus the address of ptr
. However, the new memory
address depends on the size, in bytes, of the pointer's target. This confusion can lead to
unexpected behavior.
When used with caution, pointer manipulation using ++
can
be more natural (for instance, sequentially accessing locations during
a memory test).
Polyspace Implementation
The rule checker flags operations on pointers, for example, Pointer +
Integer
, Integer + Pointer
, Pointer -
Integer
, and so on.
Troubleshooting
If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Pointers and Arrays |
Category: Advisory |
AGC Category: Advisory |
Version History
Introduced in R2024a