[previous] MISRA-C:2004  Rule  17.4:  (Required) [next] Array indexing shall be the only allowed form of pointer arithmetic.
Array indexing is the only acceptable form of pointer arithmetic, because it is clearer and hence less error prone than pointer manipulation. This rule bans the explicit calculation of pointer values. Array indexing shall only be applied to objects defined as an array type. Any explicitly calculated pointer value has the potential to access unintended or invalid memory addresses. Pointers may go out of bounds of arrays or structures, or may even point to effectively arbitrary locations.

void my_fn( uint8_t * p1, uint8_t p2[] )
{
   uint8_t index = 0U;
   uint8_t * p3;
   uint8_t * p4;

   *p1 = 0U;
   p1 ++;       /* not compliant - pointer increment               */
   p1 = p1 + 5; /* not compliant - pointer increment               */
   p1[5] = 0U   /* not compliant - p1 was not declared as an array */
   p3 = &p1[5]; /* not compliant - p1 was not declared as an array */
   p2[0] = 0U;
   index ++;
   index = index + 5U;
   p2[index] = 0U; /* compliant     */
   p4 = &p2[5];    /* compliant     */
}

uint8_t a1[16];
uint8_t a2[16];

my_fn( a1, a2 );

my_fn( &a1[4], &a2[4] );

uint8_t a[10];
uint8_t * p;
p = a;
*( p+5 ) = 0U; /* not compliant */
p[5] = 0U;     /* not compliant */


QAC messages that encompass this guideline:

0488 Performing pointer arithmetic.
0489 The integer value 1 is being added or subtracted from a pointer.
0491 Array subscripting applied to an object of pointer type.
0492 Array subscripting applied to a function parameter declared as a pointer.



(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