CodeQL 文档

返回堆栈分配的内存

ID: cpp/return-stack-allocated-memory
Kind: path-problem
Security severity: 9.3
Severity: warning
Precision: high
Tags:
   - reliability
   - security
   - external/cwe/cwe-825
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

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

此规则查找返回指向堆栈上分配的对象的指针的 return 语句。堆栈分配的内存位置的生命周期仅持续到函数返回,并且该内存的内容在之后变为未定义。显然,在函数已经返回后使用指向堆栈内存的指针将产生未定义的结果。

建议

使用 malloc 系列函数在堆上动态分配内存,以存储跨函数调用使用的数据。

示例

Record* fixRecord(Record* r) {
	Record myRecord = *r;
	delete r;

	myRecord.fix();
	return &myRecord; //returns reference to myRecord, which is a stack-allocated object
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私