gpt4 book ai didi

c - 空指针问题

转载 作者:行者123 更新时间:2023-11-30 21:23:00 24 4
gpt4 key购买 nike

我面临着 MISRA C 2004 违反规则 1.2“可能使用空指针”的情况。我使用的代码如下:

tm_uint8* diagBuf = 0u;
diagBuf[0] = diagBuf[0] + 0x40u;
diagBuf[2] = 0x01u;
diagBuf[0] = diagBuf[0] + 0x40u;
diagBuf[2] = 0x01u;

这只是上面指出的代码的一部分。有些语句有“IF”条件。

有人可以指出为什么我会违反 MISRA 规定吗?

最佳答案

根据 1999 C 标准,第 6.3.2 节“指针”,第 3 段

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

(请注意,我已删除了上面第一句话末尾对脚注的交叉引用,该脚注解释了 NULL<stddef.h> 和其他 header 中定义为空指针常量)。

这意味着

tm_uint8* diagBuf = 0u;

初始化diagBuf使用空指针常量,因为 0u是一个值为零的整数常量表达式。因此,diagBuf被初始化为空指针。

此外还有以下声明

diagBuf[0] = diagBuf[0] + 0x40u; 
diagBuf[2] = 0x01u;

两者都取消引用空指针。根据 C 标准,这是未定义的行为。

因此,报告的 Misra 违规行为是完全正确的。

在实践中,可接受此类代码的情况(例如,可以编写米斯拉规则豁免的理由,并在系统开发的背景下获得批准)非常有限。

关于c - 空指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49275540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com