メインコンテンツ

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

MISRA C:2012 Rule 21.19

The pointers returned by the Standard Library functions localeconv, getenv, setlocale or strerror shall only be used as if they have pointer to const-qualified type

説明

ルール定義

The pointers returned by the Standard Library functions localeconv, getenv, setlocale or strerror shall only be used as if they have pointer to const-qualified type. 1

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

根拠

C99 規格によると、localeconv によって返される値が指す構造体、または getenvsetlocalestrerro によって返される文字列をプログラムで変更すると、未定義の動作が発生します。さまざまな関数によって返されるポインターを const 修飾子付きかのように扱うことで、解析ツールはいずれかのポインター経由でのオブジェクトの変更の試みを検出できます。関数の戻り値を const 修飾子付きのポインターに代入することで、オブジェクトを変更しようとした場合に、コンパイラで診断が行われるようになります。

Polyspace 実装

以下の関数の出力を const でないポインターに代入する場合、Polyspace® はこのルールの違反を報告します。

  • localeconv,

  • getenv,

  • setlocale,

  • strerror

トラブルシューティング

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

すべて展開する

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

void f1(void)
{
    char* s1 = setlocale(LC_ALL, 0);    /* Non-compliant */
    struct lconv* conv = localeconv();  /* Non-compliant */
    s1[ 1 ] = 'A'; /* Non-compliant. Undefined behavior */
    conv->decimal_point = "^"; /* Non-compliant. Undefined behavior */
}

void f2(void)
{
    char str[128];
    (void) strcpy(str, setlocale(LC_ALL, 0));     /* Compliant */
    const struct lconv* conv = localeconv();      /* Compliant */
    conv->decimal_point = "^";                    /* Non-compliant. Constraint violation */
}

void f3(void)
{
    const struct lconv* conv = localeconv();  /* Compliant */
    conv->grouping[ 2 ] = 'x';                /* Non-compliant */
}

上記の例では、以下のようになります。

  • 関数 f1 内の setlocalelocaleconv の使用法は、返されたポインターを const 修飾子付きではないポインターに代入しているため準拠していません。

    メモ

    上記の setlocale および localeconv の使用法は、制約違反ではないため、コンパイラでは報告されません。ただし、解析ツールでは違反を報告できます。

  • 関数 f2 内の setlocale の使用法は、strcpyconst char * を 2 番目のパラメーターとして受け取るため準拠しています。関数 f2 内の localeconv の使用法は、返されたポインターを const 修飾子付きのポインターに代入しているため準拠しています。ポインターが指すオブジェクトを変更しようとすると、制約違反になるため、コンパイラまたは解析ツールによって報告されます。

  • 関数 f3 内の const 修飾子付きのポインターの使用法は、localeconv から返された値にコンパイル時の保護が提供されますが、それが参照する文字列には同じことが当てはまりません。このような文字列の変更は解析ツールで検出できます。

チェック情報

グループ: 標準ライブラリ
カテゴリ: 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.