メインコンテンツ

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

  • new または delete の非配置形式

  • 名前空間 std で囲まれたメンバー関数 allocate または deallocate

  • 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
}

この例では以下のようになります。

  • 非配置形式の new および delete 演算子を使用したクラス MyClass のオブジェクトに対するメモリの動的割り当てと割り当て解除は準拠していません。

  • malloccallocfree の使用は準拠していません。

チェック情報

グループ: 言語サポート ライブラリ
カテゴリ: 必要

バージョン履歴

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.