主要内容

MISRA C++:2023 Rule 21.6.1

R2026b

Dynamic memory should not be used

自 R2024b 起

描述

Dynamic memory should not be used 1

理由

使用动态内存可能导致内存泄漏、资源耗尽和非确定性执行时间等安全问题。程序可以显式或隐式地使用动态内存,而避免使用动态内存可能很困难。很少有程序能够完全避免使用动态内存。

如果必须使用动态内存,请提供理由和支持文档,说明如何管理工程中的任何潜在问题。

为了尽量减少内存管理缺陷,软件设计应针对管理已分配内存的生命周期制定明确的策略。例如:

  • 明确定义软件的哪些部分负责已分配内存,以便每一段已分配内存都有已知的所有者负责其生命周期。

  • 优先使用简单的所有权模型,例如唯一所有权 (std::unique_ptr),而不是更复杂的共享所有权模型。简单的所有权模型更易于理解,并能降低出错风险。

  • 使用 std::shared_ptr 等引用计数机制来管理生命周期时务必谨慎,因为它们可能因循环引用而导致内存泄漏。在设计关系时,应避免此类场景,或者使用弱指针 (std::weak_ptr) 来打破潜在的循环引用。

  • 将动态内存(例如分配或释放函数)的执行限制在程序生命周期的非必要阶段。例如,通过在初始化阶段启用这些调用并立即填充已分配内存,可以在分配时识别内存耗尽问题。

Polyspace 实现

Polyspace® 会对以下动态内存使用报告违规。

  • 使用 operator new 或 operator delete 管理动态存储操作的对象。

  • calloc、malloc、realloc、aligned_alloc 和 free 函数。

  • 平台特定的内存分配或释放函数。

    .

  • 隐式使用动态内存。例如,当您实例化一个容器而未显式指定分配器时,默认使用 std::allocator。

    #include <vector>
    #include <memory>
    
    int main() {
        std::vector<int> myVector; // Noncompliant
                                   // Uses std::allocator<int> implicitly
    }

故障排除

如果您预期会出现违规,而 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
}

在此示例中:

  • 使用 new 和 delete 运算符对 MyClass 对象进行动态内存分配和释放是不合规的。

  • 使用 malloc、calloc 和 free 是不合规的。

检查信息

组:语言支持库
类别:建议
PQL 名称:std.misra_cpp_2023.R21_6_1

版本历史记录

在 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:2025

  • MISRA C++:2008

  • MISRA C++:2023

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