gpt4 book ai didi

c - 失去不稳定资格

转载 作者:行者123 更新时间:2023-11-30 15:10:27 24 4
gpt4 key购买 nike

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

下面的代码是模块“主模块”的一部分,它拥有 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];)抛出警告“Msg(7:0312)危险的指针转换导致失去 volatile 资格.”上述警告是强制警告,因此有必要解决它。

我确实明白,我将 volatile 变量的地址分配给 void 指针,这会导致失去 volatile 资格。我尝试了不同的方法试图解决该警告,但无法得到结论性的方法。

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

最佳答案

如果您将值分配给 volatile 对象或读取 volatile 对象的值而不使用 volatile 限定指针,则会出现未定义的行为。

编译器必须以比非 volatile 对象更严格的方式对待 volatile 对象(这意味着将非 volatile 对象视为 volatile 对象很好,将 volatile 对象视为非 volatile 对象可能会产生不好的结果)结果)。

将 volatile 对象的地址转换为非 volatile 指针会让您面临严重的风险。不要这样做。无论谁使用该 void* 指针,都有调用未定义行为的巨大风险。例如,仅使用 memcpy 复制该 volatile 数组是未定义的行为。任何事情,通常是坏事,都可能发生。

将该函数声明为

boolean GetConditionalBuffer(volatile x_tst **PtrToBuffer)

因为 volatile x_tst* 是它存储到 PtrToBuffer 中的内容。为什么要丢弃类型信息?我实际上会将其更改为

volatile x_tst* GetConditionalBuffer (void);

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

关于c - 失去不稳定资格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36126500/

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