MISRA C 2012规则9.1读取未初始化的值 [英] MISRA C 2012 Rule 9.1 Reading uninitialized value

查看:388
本文介绍了MISRA C 2012规则9.1读取未初始化的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临着违反规则9.1的情况. 我想在初始化之前读取一个自动变量(在声明时具有垃圾值),并在不为null的情况下分配null.如果为null,则使用不同的值. 示例代码:

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(); 
        } 
    } 
}

违反是针对行if (var1[reg_num] != VAR_NULL)的,其中var1[reg_num]在初始化之前正在读取.

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

有没有办法编写相同的代码而不违反9.1

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

推荐答案

该工具可正确报告错误.

The tool is correct to report the error.

引用C11,第§6.7.9章

Quoting C11, chapter §6.7.9

如果未自动初始化具有自动存储期限的对象,则其值为 不定. [....]

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

为避免这种情况,可以在定义时将数组初始化为某个值,例如0.这样,您在每个元素中都有一个 predictable 值.

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.

这篇关于MISRA C 2012规则9.1读取未初始化的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆