在为嵌入式系统编程时,通常不允许使用malloc().大部分时间我都能够处理这个问题,但有一件事让我感到恼火:它使我无法使用所谓的"不透明类型"来启用数据隐藏.通常我会做这样的事情:
// In file module.h
typedef struct handle_t handle_t;
handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);
// In file module.c
struct handle_t {
int foo;
void *something;
int another_implementation_detail;
};
handle_t *create_handle() {
handle_t *handle = malloc(sizeof(struct handle_t));
// other initialization
return handle;
}
Run Code Online (Sandbox Code Playgroud)
你去:create_handle()执行malloc()来创建'实例'.通常用于防止必须使用malloc()的构造是更改create_handle()的原型,如下所示:
void create_handle(handle_t *handle);
Run Code Online (Sandbox Code Playgroud)
然后调用者可以这样创建句柄:
// In file caller.c
void i_am_the_caller() {
handle_t a_handle; // Allocate a handle on the stack instead of malloc()
create_handle(&a_handle);
// ... a_handle …Run Code Online (Sandbox Code Playgroud) 我目前正在开发一个项目,要求代码符合Misra 2012标准.在整个项目中,我们有许多必需的misra警告告诉我们,我们无法将指针转换为指向另一种类型的指针.事情就像void *memcpy(void *to, const void *from, size_t n)产生两个Misra必需的警告一样简单,因为需要分别将类型转换为void*和const void*.从void*转换为指向任何其他类型的指针也会发出Misra警告.
我的问题是Misra如何在没有任何警告被抛出的情况下期望malloc和其他所有工作?即使将void*缓冲区转换为uint8_t*缓冲区来逐字节解析abuffer并填充结构结构的所有元素也会引发大量警告?
而不是这些警告,它不仅可以显示使用注释或信息要求我们仔细检查包装,对齐和其他可能出错的地方吗?