メインコンテンツ

MISRA C:2012 Rule 21.20

The pointer returned by the Standard Library functions asctime, ctime, gmtime, localtime, localeconv, getenv, setlocale or strerror shall not be used following a subsequent call to the same function

説明

ルール定義

The pointer returned by the Standard Library functions asctime, ctime, gmtime, localtime, localeconv, getenv, setlocale or strerror shall not be used following a subsequent call to the same function. 1

This rule comes from MISRA C™:2012 Amendment 1.

根拠

上記の関数は、標準ライブラリ内のオブジェクトへのポインターを返します。このオブジェクトの実装は静的バッファーを使用できますが、同じ関数の 2 回目の呼び出しによってこのバッファーが変更される可能性があります。そのため、ポインターを使ってアクセスする値は、同じ関数を次に呼び出す前に予期せず変更される可能性があります。

トラブルシューティング

ルール違反を想定していてもその違反が表示されない場合、コーディング規約違反が想定どおりに表示されない理由の診断を参照します。

すべて展開する

#include <stdio.h>
#include <locale.h>
#include <string.h>

void f1(void)
{
    const char* res1;
    const char* res2;
    char copy[ 128 ];
    res1 = setlocale(LC_ALL, 0);
    (void) strcpy(copy, res1);
    res2 = setlocale(LC_MONETARY, "French");
    printf("%s\n", res1);    /* Non-compliant */
    printf("%s\n", copy);    /* Compliant */
    printf("%s\n", res2);    /* Compliant */
}

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

  • 最初の printf ステートメントは、setlocale が返すポインターを同じ関数の次の呼び出しに使用して res2 に代入しているため、準拠していません。

  • 2 番目の printf ステートメントは、関数 setlocale を次に呼び出す前に strcpy によってコピー操作を実行するため、準拠しています。

  • 3 番目の printf ステートメントは、使用前に関数 setlocale の次の呼び出しが行われていないため、準拠しています。

チェック情報

グループ: 標準ライブラリ
カテゴリ: Mandatory
AGC カテゴリ: Mandatory

バージョン履歴

R2017a で導入


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.