[previous] MISRA-C:2004  Rule  17.2:  (Required) [next] Pointer subtraction shall only be applied to pointers that address elements of the same array.
Subtraction of pointers only gives well-defined results if the two pointers point (or at least behave as if they point) into the same array object.

Example Code:


/* PRQA S 2982, 2984 ++ */

#include "misra.h"
#include "m2cmex.h"


extern S16 test_1702( void )
{
   PC arr[] = "text";
   PC *ch   = arr;
   PC *last = &arr[ 3 ];

   S32 a     = 1;
   S32 *p_a1 = &a;
   S32 *p_a2 = &a;

   struct
   {
      S32 xx;
      S32 yy;
   } b1, b2;

   S32 *p_b1;
   S32 *p_b2;
   S16 nch;

   nch = ( last - ch ) + 1;

   nch = p_a2 - p_a1;

   p_b1 = &b1.xx;
   p_b2 = &b1.yy;
   nch = p_b2 - p_b1;             /* MISRA Violation */

   p_b1 = &b1.xx;
   p_b2 = &b2.yy;
   nch = p_b2 - p_b1;             /* MISRA Violation */

   return nch;
}


QAC messages that encompass this guideline:

2771 Definite: These pointers address different objects.
2772 Apparent: These pointers address different objects.


Related rules:

Rule  17.3 >, >=, <, <= shall not be applied to pointer types except where they point to the same array.



(c) The Motor Industry Research Association, 2004
QA C Source Code Analyser 8.1.2
MISRA-C:2004 Compliance Module 3.2
© 2013 Programming Research
www.programmingresearch.com
Personality Groups | Glossary | Message Index | MISRA-C:2004 Rule Index Contents