2023-05-03 11:06:20 +02:00
|
|
|
== Why is this an issue?
|
|
|
|
|
2021-04-28 16:49:39 +02:00
|
|
|
Attempting to make a comparison between pointers using >, >=, < or +<=+ will produce undefined behavior if the two pointers point to different arrays.
|
|
|
|
|
|
|
|
Additionally, directly comparing two arrays for equality or inequality has been deprecated in {cpp}.
|
|
|
|
|
|
|
|
However, equality or inequality between an array and a pointer is still valid
|
|
|
|
|
2021-04-28 18:08:03 +02:00
|
|
|
|
2023-05-03 11:06:20 +02:00
|
|
|
=== Noncompliant code example
|
2021-04-28 16:49:39 +02:00
|
|
|
|
2022-02-04 17:28:24 +01:00
|
|
|
[source,cpp]
|
2021-04-28 16:49:39 +02:00
|
|
|
----
|
|
|
|
void f1 ( )
|
|
|
|
{
|
|
|
|
int a1[ 10 ];
|
|
|
|
int a2[ 10 ];
|
|
|
|
int * p1 = a1;
|
|
|
|
if ( p1 < a2 ) // Non-compliant, p1 and a2 point to different arrays.
|
|
|
|
{
|
|
|
|
}
|
|
|
|
if ( p1 - a2 > 0 ) // Non-compliant, p1 and a2 point to different arrays.
|
|
|
|
{
|
|
|
|
}
|
|
|
|
if ( a1 == a2) // Non-compliant (in C++). Comparing different array for equality is deprecated
|
|
|
|
{
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
2021-04-28 18:08:03 +02:00
|
|
|
|
2023-05-03 11:06:20 +02:00
|
|
|
=== Compliant solution
|
2021-04-28 16:49:39 +02:00
|
|
|
|
2022-02-04 17:28:24 +01:00
|
|
|
[source,cpp]
|
2021-04-28 16:49:39 +02:00
|
|
|
----
|
|
|
|
void f1 ( )
|
|
|
|
{
|
|
|
|
int a1[ 10 ];
|
|
|
|
int * p1 = a1;
|
|
|
|
if ( p1 < a1 ) // Compliant, p1 and a1 point to the same array.
|
|
|
|
{
|
|
|
|
}
|
|
|
|
if ( p1 - a1 > 0 ) // Compliant, p1 and a1 point to the same array.
|
|
|
|
{
|
|
|
|
}
|
|
|
|
if ( p1 == a2 ) // Compliant, comparing a pointer and an array for equality is valid
|
|
|
|
{
|
|
|
|
}
|
|
|
|
}
|
|
|
|
----
|
|
|
|
|
2021-04-28 18:08:03 +02:00
|
|
|
|
2023-05-03 11:06:20 +02:00
|
|
|
== Resources
|
2021-04-28 16:49:39 +02:00
|
|
|
|
|
|
|
* MISRA C:2004, 17.3 - >, >=, <, +<=+ shall not be applied to pointer types except where they point to the same array.
|
|
|
|
* MISRA {cpp}:2008, 5-0-18 - >, >=, <, +<=+ shall not be applied to objects of pointer type, except where they point to the same array.
|
2023-12-20 10:08:18 +01:00
|
|
|
* {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#es62-dont-compare-pointers-into-different-arrays[ES.62: Don't compare pointers into different arrays]
|
2021-04-28 18:08:03 +02:00
|
|
|
|
2021-06-02 20:44:38 +02:00
|
|
|
|
2021-06-03 09:05:38 +02:00
|
|
|
ifdef::env-github,rspecator-view[]
|
2021-06-08 15:52:13 +02:00
|
|
|
'''
|
2021-06-02 20:44:38 +02:00
|
|
|
== Comments And Links
|
|
|
|
(visible only on this page)
|
|
|
|
|
2023-05-25 14:18:12 +02:00
|
|
|
=== is related to: S939
|
|
|
|
|
|
|
|
=== is related to: S940
|
|
|
|
|
2021-06-03 09:05:38 +02:00
|
|
|
endif::env-github,rspecator-view[]
|