メインコンテンツ

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

MISRA C++:2008 Rule 7-5-2

The address of an object with automatic storage shall not be assigned to an object that may persist after the object has ceased to exist.

説明

ルール定義

The address of an object with automatic storage shall not be assigned to an object that may persist after the object has ceased to exist. 1

根拠

オブジェクトが別のオブジェクトを指していて、後者のオブジェクトが存在しなくなった "後も" 指し続けている場合、前者のオブジェクトのデリファレンスは未定義の動作につながります。

Polyspace 実装

自動ストレージ オブジェクトのアドレスを、それよりも有効期間が長いオブジェクトに代入すると、Polyspace® はこのルールの違反を報告します。有効期間がより長いオブジェクトには、次のものがあります。

  • グローバル ポインター変数

  • 外側のスコープで宣言されたローカル オブジェクト

関数がローカル変数のアドレスを返す場合、チェッカーはこのルールの違反を報告しません。この状況は、MISRA C++:2008 Rule 7-5-1 に含まれています。

トラブルシューティング

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

すべて展開する

char * ptr;
 
void foo (void) {
    char varInFoo;
    ptr = &varInFoo; //Noncompliant
}

void bar (void) {
    char varInBar = *ptr;
}

void main() {
    foo();
    bar();
}

代入 ptr = &varInFoo は非準拠です。グローバル ポインター ptr は関数 foo の外部でデリファレンスされる可能性があるからです。この場合、変数 varInFoo は既にスコープを外れています。たとえば、この例では ptr が関数 bar でデリファレンスされていますが、呼び出されるのは foo の実行完了後です。

この例では、内側のスコープにあるローカル オブジェクトのアドレスが、それよりも有効期間が長いポインター pointer_outer_scope に代入されます。

#include <cstdint>

void foo()
{
	int8_t *pointer_outer_scope;
	{
		int8_t local_var;
		int8_t local_array[ 10 ];
		int8_t *pointer_inner_scope = nullptr;
		pointer_outer_scope = &local_var;                  // Noncompliant
		pointer_outer_scope = local_array;             // Noncompliant
		pointer_inner_scope = &local_var;                  //Compliant
		pointer_outer_scope = pointer_inner_scope;     // Rule does not apply

	}
}

このルールでは、潜在的に未接続になるポインターおよび参照のトリビアルなインスタンスと特定のインスタンスがチェックされます。たとえば、代入 pointer_outer_scope = pointer_inner_scope により、ポインターが未接続になります。この代入はローカル オブジェクトのアドレスを明示的に pointer_outer_scope に代入しないため、このルールは適用されません。

チェック情報

グループ: Declarations
カテゴリ: 必要

バージョン履歴

R2013b で導入


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.