メインコンテンツ

AUTOSAR C++14 Rule A18-5-9

Custom implementations of dynamic memory allocation and deallocation functions shall meet the semantic requirements specified in the corresponding "Required behaviour" clause from the C++ Standard

説明

ルール定義

Custom implementations of dynamic memory allocation and deallocation functions shall meet the semantic requirements specified in the corresponding "Required behaviour" clause from the C++ Standard.

根拠

C++ 標準 ([new.delete]) では、動的割り当て/割り当て解除関数に必要な特定の動作が規定されています。これらの意味論的要件を満たしていないグローバル置換割り当て/割り当て解除関数を実装すると、必要な動作に依存している他の関数が未定義の方法で動作する可能性があります。

たとえば、void* operator new ( std::size_t count ) は、要求されたメモリ量の割り当てに失敗した場合に bad_alloc 例外をスローするように想定されています。スローする代わりに nullptr を返す置換割り当て関数を実装した場合は、メモリ割り当ての失敗時にスローを想定していた関数が、代わりに null ポインターをデリファレンスしようとする可能性があります。

Polyspace 実装

Polyspace® は、動的割り当て/割り当て解除関数の以下の置換実装にフラグを設定します。

  • 想定される動作が、エラー時に bad_alloc 例外をスローすることである場合に、nullptr を返す置換 operator new

  • 想定される動作がスローしないことである場合に、エラー時に直接的または間接的にスローする置換 operator new または operator delete。Polyspace は、コード内のスローの位置も強調表示します。

トラブルシューティング

ルール違反が想定されるものの、Polyspace から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。

すべて展開する

#include<new>

extern void* custom_alloc(std::size_t);

void* operator new (std::size_t count) //Non-compliant
{
    return custom_alloc(count);
}

void func()
{
    int* ptr1;
    try {
        ptr1 = new int;
    } catch (const std::bad_alloc&) {
        //handle exception
    }

    //Use ptr1

}

この例では、他の場所で定義されたカスタム割り当て関数 custom_alloc がエラー時に nullptr を返す可能性があります。メモリ割り当てに失敗した場合に bad_alloc 例外を想定している関数 func が NULL ポインターをデリファレンスする可能性があります。これは、operator new がスローしないためです。

チェック情報

グループ: 言語サポート ライブラリ
カテゴリ: Required、Automated

バージョン履歴

R2020b で導入