失去资格的挥发性

时间:2016-03-21 08:52:31

标签: c pointers volatile

我在一些安全关键汽车模块中运行了代码。以下是对代码的粗略估计:

以下代码是模块的一部分 - "主要模块" ,拥有volatile变量/数组" x_ast"

Main Module.c

//The structure x contains the major data that needs to be stored in case of a crash event. i.e. a real car crash
// x contains data such a vehicle speed, environment data, sensor data, CAN related data,etc. Basically x itself has lot of structures inside it.


typedef struct x x_tst;
volatile x_tst x_ast[5];
//x_ast is being used in realtime and background functions, considering proper interrupt disabling and enabling.

以下代码是模块的一部分 - " DependentModule"这样可以共享缓冲区" x_ast"。

DependentModule.c

extern volatile x_tst x_ast[5];


//x_ast is owned by a separate module
//Now I need to share this buffer "x_ast" to a different module that will inturn fill data in it for some conditions. Say for a particular condition that is activated, the buffer "x_ast" will be shared across to a module "Conditional Data Record". 
//The base address of first indexed buffer "x_ast[1]" is provided to "Conditional Data Record" for access. 
//The main module will not access the buffer that is shared, once the "Conditional Data Record" is activated/requested. 

// Below is a mechanism to share the buffer "x_ast" to module "Conditional Data Record".

// This API will be called by module - "Conditional Data Record" once it is activated. It is ensured that this takes place only during intialization of whole system, and no other time.

boolean GetConditionalBuffer(uint8 **PtrToBuffer)
{
  boolean BufferShared = FALSE;
  void* Temp_ptr;
  *PtrToBuffer = NULL;

// if module  "Conditional Data Record" is activated? then share the buffer "x_ast", else do not share the buffer.

if(Conditional Data Record == activated) {
   Temp_ptr = (x_tst*)&x_ast[1];
   *PtrToBuffer = Temp_ptr;
   BufferShared = TRUE;
}

return BufferShared;

}



Referring to the line of code:
Temp_ptr = (x_tst*)&x_ast[1];

以上代码行(Tempptr =(x_tst *)& x_ast [1];)会发出警告" 消息(7:0312)危险指针投射结果失去资格。" 上述警告是强制性警告,因此有必要解决它。

我明白我正在为void指针分配一个volatile变量的地址,导致挥发性资格的丢失。 我尝试过尝试解决警告的不同方法,但无法得出确定的方法。

有什么办法,我可以修改代码并删除此警告,或者可以绕过此警告。

1 个答案:

答案 0 :(得分:1)

如果为volatile对象赋值或在不使用volatile限定指针的情况下读取volatile对象的值,则会得到未定义的行为。

编译器必须以比非易失性对象更严格的方式处理易失性对象(这意味着将非易失性对象视为易失性就好了,将易失性对象视为非易失性对象可能有坏处理后果)。

将易失性对象的地址强制转换为非易失性指针 会使您面临极大的风险。不要做。使用该void *指针的人很有可能调用未定义的行为。例如,仅使用memcpy复制易失性数组是未定义的行为。任何事情,通常是坏事,都可能发生。

将该函数声明为

boolean GetConditionalBuffer(volatile x_tst **PtrToBuffer)

因为volatile x_tst *是它存储在PtrToBuffer中的内容。你为什么要扔掉类型信息?我实际上将其改为

volatile x_tst* GetConditionalBuffer (void);

这使得开发人员的大脑变得更容易,并使该功能更易于使用。