CodeQL 文档

指针算法中使用的向上转型数组

ID: cpp/upcast-array-pointer-arithmetic
Kind: path-problem
Security severity: 9.3
Severity: warning
Precision: high
Tags:
   - correctness
   - reliability
   - security
   - external/cwe/cwe-119
   - external/cwe/cwe-843
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

当将指向派生类的指针作为参数传递给预期指向基类型的指针的函数时,它可能会被隐式转换为指向其基类型的指针。如果随后使用指针算法或数组解引用,则将使用基类型的大小执行该操作。这可能导致从派生类型中的意外字段读取数据。

建议

仅转换指向单个对象的指针。如果必须处理转换为基类型的一系列对象,请使用指针数组而不是指向数组的指针。

示例

class Base {
public:
	int x;
}

class Derived: public Base {
public:
	int y;
};

void dereference_base(Base *b) {
	b[2].x;
}

void dereference_derived(Derived *d) {
	d[2].x;
}

void test () {
	Derived[4] d;
	dereference_base(d); // BAD: implicit conversion to Base*

	dereference_derived(d); // GOOD: implicit conversion to Derived*, which will be the right size
}
  • ©GitHub 公司
  • 条款
  • 隐私