MISRA C 2012 Rule 9.1 Reading uninitialized value

I came across a scenario when rule 9.1 is violated. I want to read an automatic variable (having garbage value when declared) before initialization and set it to null if it is not zero. If it is zero, then with a different value. Code example:

{ 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 for the line if (var1[reg_num] != VAR_NULL) , where var1[reg_num] is read before initialization.

Is it possible to write the same code without breaking 9.1

-2
source share
3 answers

The tool correctly reports an error.

Citation C11 , chapter ยง6.7.9

If an object with automatic storage duration is not explicitly initialized, its value is undefined. [....]

To avoid this, you can initialize the array to some value, for example, 0 when defining. Thus, you have a predictable value present in each of the elements.

To add, there is no sense in the above logic (i.e. checking the value of an uninitialized variable in general), in the best case it will call undefined . Do not do that.

+1
source

All you have to do is initialize the variables. This is practically rule number 2 when learning C - a very, very basic material. The MISRA rule simply tells 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 an initialized variable, the array initialization code is simplified for granted. In case you missed it, you need to initialize the variables when you define them.

+1
source

Despite the fact that some MISRA rules border on bizarre idiosyncratic dogmatic pedantics, this question of reading uninitialized variables is directly removed from the language itself: with some exceptions, the behavior when reading an uninitialized variable is undefined.

Do not : MISRA or MISRA.

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

-1
source

Source: https://habr.com/ru/post/1274189/


All Articles