メインコンテンツ

MISRA C:2012 Rule 21.17

Use of the string handling function from <string.h> shall not result in accesses beyond the bounds of the objects referenced by their pointer parameters

説明

ルール定義

Use of the string handling function from <string.h> shall not result in accesses beyond the bounds of the objects referenced by their pointer parameters. 1

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

根拠

文字列処理関数の不適切な使用は、関数引数の範囲外への読み取りまたは書き込みアクセスが発生し、未定義の動作につながる可能性があります。

トラブルシューティング

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

すべて展開する

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

char string[] = "Short";
void f1(const char* str)
{
    (void) strcpy(string, "Too long to fit");      /* Non-compliant */
    if (strlen(str) < (sizeof(string) - 1u)) {
        (void) strcpy(string, str);      /* Compliant */
    }
}

size_t f2(void)
{
    char text[ 5 ] = "Token";
    return strlen(text);    /* Non-compliant */
}

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

  • strcpy の最初の使用法は、コピー先引数の string の末尾を超えて書き込もうとするため準拠していません。

  • strcpy の 2 つ目の使用法は、コピー元引数の str がコピー先引数 string に収まる場合のみ書き込もうとするため準拠しています。

  • strlen の使用法は準拠していません。strlen は、null 終端までの文字列の長さを計算します。文字配列 text には null 終端が含まれていません。

チェック情報

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