Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MISRA incrementation in C

While debugging some embedded code, I came across something like this:

buffPtr = &a[5];
buffEndPtr = &a[10];

while (buffPtr != buffEndPtr) 
{ 
    *buffPtr = 0xFF; 
    buffPtr  = &buffPtr[1];         /*  MISRA improvement for: buffPtr++ */ 
}

Why would this construct be an improvement over (*buffPtr)++ ?

like image 616
Adrian Suciu Avatar asked May 14 '15 14:05

Adrian Suciu


1 Answers

There is a MISRA rule that states the only pointer math allowed is the indexing operation.

The pattern you have shown is a poorly executed work-around. It is ugly/weird/uncommon and probably based on a misunderstanding of the purpose of that rule. It may also violate another rule.

A better way to write this code would be:

for(i=5; i < 10; i++)
{
    a[i] = 0xff;
}

Update 2015-05-20 - Since this was the accepted answer here's the actual rule violated, courtesy of embedded.kyle:

MISRA-C:2004, Rule 17.4 (Required) or MISRA-C:2012, Rule 18.4 (Required) Array indexing shall be the only allowed form of pointer arithmetic.

like image 129
Brian McFarland Avatar answered Sep 22 '22 06:09

Brian McFarland