主要内容

MISRA C++:2023 Rule 21.6.2

Dynamic memory shall be managed automatically

自 R2024b 起

描述

Dynamic memory shall be managed automatically 1

理由

需要管理动态内存,以避免出现内存泄漏、重复释放、悬空指针以及分配和释放函数不匹配等错误。尝试在不使用 std::make_uniquestd::vector 等功能的情况下管理动态内存很容易出错。请勿使用 C 样式的内存分配函数,因为它们存在类型不安全以及不使用构造函数或析构函数等限制。

Polyspace 实现

Polyspace® 会针对以下任何一种非自动使用动态内存管理的情形报告违规:

  • malloccallocreallocalligned_allocfree 函数

  • 非放置形式的 newdelete

  • 命名空间 std 中名为 allocatedeallocate 的成员函数

  • 使用 std::unique_ptr::release

故障排除

如果您预期会出现违规,而 Polyspace 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#include <cstdlib>
#include <iostream>

class MyClass {
public:
    MyClass() { std::cout << "Constructor called\n"; }
    ~MyClass() { std::cout << "Destructor called\n"; }
};

int exampleClass() {
    MyClass* myObject = new MyClass();     // Noncompliant
    delete myObject;                       // Noncompliant
}

int main() {
	exampleClass();
    int* arr = static_cast<int*>(std::malloc(5 * sizeof(int)));    // Noncompliant
    int* arr_c = static_cast<int*>(std::calloc(5, sizeof(int)));   // Noncompliant
    std::free(arr);                                                // Noncompliant
    std::free(arr_c);                                              // Noncompliant
}

在此示例中:

  • 使用非放置形式的 newdelete 运算符对类 MyClass 的对象进行动态内存分配和释放是不合规的。

  • 使用 malloccallocfree 是不合规的。

检查信息

组:语言支持库
类别:必需
PQL 名称:std.misra_cpp_2023.R21_6_2

版本历史记录

在 R2024b 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.