MISRA C++-2008 Rule 5-0-15 - Array indexing shall be the only form of pointer arithmetic

依然范特西╮ 提交于 2019-12-06 15:54:07

问题


I need someone who has more experience with MISRA to help me to solve this. I have the following code:

byte* buf = new(std::nothrow) byte[bufferSize];

.....
for (uint32_t i = 0; i < bufferSize; i+=4)
{

..............
                        {
buf[ i+0 ] = b;
buf[ i+1 ] = g;
buf[ i+2 ] = r;

(1) Event misra_violation:  [Required] MISRA C++-2008 Rule 5-0-15 violation: Array indexing shall be the only form of pointer arithmetic.
buf[ i+3 ] = a;

}

MISRA Rule 5-0-15 doesn't allow also ptr++ or ptr--. What should be the approach here to increment/decrement and assign values using pointers created by new?

My MISRA checker is Coverity 7.0.3.3.


回答1:


There is no problem with your code. It uses array indexing as required. Your static analyser is broken.




回答2:


I feel the "for" should have condition with "i+3".

for (uint32_t i = 0; i+3 < bufferSize; i+=4)

This could solve the problem. Let me know if it solves.




回答3:


Ok, I found a way this to work:

byte* buf = new(std::nothrow) byte[bufferSize];
.....
for (uint32_t i = 0; i < bufferSize; i+=4)
{
  ..............           
  uint32_t k = i;
  buf[k] = b;
  k++;
  buf[k] = g;
  k++;
  buf[k] = r;
  k++;
  buf[k] = a;
}

It seems that MISRA does not likes the index arithmetic to be inside the [] brackets. I am not sure if this is not a bug in the tool, maybe it is fixed in the newer Coverity tools.

The following DO NOT work ( MISRA again complains with Rule 5-0-15 violation):

byte* buf = new(std::nothrow) byte[bufferSize];
.....
for (uint32_t i = 0; i < bufferSize; i+=4)
{
  ..............           
  uint32_t k = i;
  buf[k++] = b;
  buf[k++] = g;
  buf[k++] = r;
  buf[k++] = a;
}


来源:https://stackoverflow.com/questions/34015315/misra-c-2008-rule-5-0-15-array-indexing-shall-be-the-only-form-of-pointer-ar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!