☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

合理使用 reinterpret_cast

12.21 ID_forbidReinterpretCast
目录 › next › previous

reinterpret_cast 是一种不安全的类型转换,如果必须使用需提供合理的注释说明。

示例:

class MyData { .... };

void foo(const char* path) {
    unsigned char* p = read_from_file(path);
    MyData* dat = reinterpret_cast<MyData*>(p);  // Bad
    ....
}

设例中 read_from_file 读取并返回文件的二进制数据,用 reinterpret_cast 将二进制数据直接转为对象是不安全的,妥善的做法是根据文件数据将对象的成员逐一构造出来,可参见 ID_stricterAlignedCast 介绍的方法,这样也可以及时发现并处理问题。

又如:

ext_type* ext_interface();   // External interface

void foo() {
    auto* raw = ext_interface();
    auto* dat = reinterpret_cast<MyType*>(raw);   // OK
    ....
}

例中 ext_interface 是不受控制的外部接口,它的返回类型不完整或不可用,甚至返回的地址也不遵循 C++ 内存模型,需要将其“重解释”为另一种类型才能探究其内部结构和数据,MyType 是为了解决这个问题而自定义的类型,这种情况可以使用 reinterpret_cast 完成这种非常规转换,但需注明这种情况产生的原因。

相关

ID_forbidCStyleCast ID_stricterAlignedCast

参考

CWE-843 C++ Core Guidelines Pro.safety
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.