MISRA C 2012 Rule 9.1 Reading uninitialized value [duplicate]

泪湿孤枕 提交于 2019-12-14 03:27:43

问题


I am facing scenario where rule 9.1 getting violated. I want to read an auto variable(having garbage value while declaring) before initialization and to assign null if it is not null. If it is null, then with different value. Sample code:

{ 
    int8_t reg_num; 
    uint64_t var1[NUM]; 
    for (reg_num = 0; reg_num < NUM; reg_num++) {
        if (var1[reg_num] != VAR_NULL) { 
            var1 [reg_num] = VAR_NULL; 
        } else { 
            var1[reg_num] = func1(); 
        } 
    } 
}

Violation is for the line if (var1[reg_num] != VAR_NULL) where var1[reg_num] is reading before initialization.

Is there any way to write the same code without violating 9.1


回答1:


All you have to do is initialize your variables. This is practically rule #2 when learning C -- very, very basic material. The MISRA rule is just telling you to follow the basic rules in C.

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>

#define NUM 10

/* assumes your VAR_NULL is zero */
#define VAR_NULL 0LLU

uint64_t func1(void)
{
  return 3LLU;
}

int main(void)
{
  int8_t reg_num = 0;
  uint64_t var1[NUM] = { 0LLU };
  for (; reg_num < NUM; reg_num++)
  {
    var1[reg_num] = func1();
  }
  getchar();
  return 0;
}

With the initialized variable, the array initialization code is simplified as a matter of course. In case you missed it, the point is to initialize variables when you define them.




回答2:


The tool is correct to report the error.

Quoting C11, chapter §6.7.9

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [....]

To avoid this, you can initialize the array to some value, say, 0 while defining. This way, you have a predictable value present in each of the elements.

To add, it makes no sense of the logic stated above (i.e., checking a value of an uninitilized variable, in general), at best, it will invoke undefined behavior. Don't do it.




回答3:


Although some of MISRA's rules are bordering on whimsical idiosyncratic dogmatic pedantry, this one about reading uninitialised variables is directly lifted from the language itself: with a few exceptions the behaviour on reading an uninitialised variable is undefined.

Don't do it: MISRA or no MISRA.

In your case you can write uint64_t var1[NUM] = {0};



来源:https://stackoverflow.com/questions/47880155/misra-c-2012-rule-9-1-reading-uninitialized-value

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