c - 在嵌入式中取消引用 NULL 指针

标签 c pointers embedded non-volatile

我在我的项目中使用 Renesas V850 系列微 Controller 。 我的产品使用与主程序部分分开的非 volatile 内存块(NVRam block )位置。在运行时,这些 NVRAM block 会受到监控,以验证它们是否未损坏。此检查是使用类似于下面给出的代码完成的:

逻辑 1

if((NULL != pBlock_One_Pointer) &&  (BLOCK_ONE_ID != *(((const tUI8*)pBlock_One_Pointer) + ID_OFFSET))) 
{
.....Do some corrective action....
}

此代码的问题是,如果指针“pBlock_One_Pointer”以某种方式被损坏,值为“NULL”,则 Block_ID 检查(“if”语句的第二部分未完成)。

避免这种情况的一种方法是删除“if”条件的第一部分,它会检查 Block_ID,而不管指针是否为“NULL”,如下所示

逻辑 2

if (BLOCK_ONE_ID != *(((const tUI8*)pBlock_One_Pointer) + ID_OFFSET))

但是如果“pBlock_One_Pointer”指向NULL,会不会引发异常?

所以基本上我有 2 个问题:

  1. 是否有可能由于运行时的某些损坏导致指针变为 NULL 指针?
  2. 如果是这样,Logic 2 会帮助我克服它吗?

最佳答案

But if "pBlock_One_Pointer" points to NULL, will it cause a exception ?

它会导致未定义的行为。

根据 the C standard6.5.3.2 地址和间接运算符 :

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.
If the operand has type ‘‘pointer to type ’’, the result has type ‘‘ type ’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

所以:

Is there a chance that pointer becomes NULL pointer due to some corruption during runtime?

是的。这是可能的。

If so , will Logic 2 help me to overcome it?

没有。怎么可能呢?您要检查损坏的内存位置已丢失。

关于c - 在嵌入式中取消引用 NULL 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47889478/

相关文章:

Curl:这个curl语句涉及到哪些API调用?

c - 如何在大指针中打印字节子集?

c - 在 C 中与 STM32 芯片的内存交互

embedded - 嵌入式C程序中的高效位校验

C 编译器无法在 Linux 系统上创建可执行文件

c - 错误 : variable or field 'dtra' declared void

objective-c - X代码 4.3 : Static Library Generation

c - 如何将浮点输入转换为整数并保持最大精度?

c - 指向函数的 Typedef 结构指针 (C)

c - 将格式化输出发送到 C 中的字符数组元素