メインコンテンツ

ISO/IEC TS 17961 [xfilepos]

fgetpos が返す値以外の値を fsetpos で使用

説明

ルール定義

fgetpos が返す値以外の値を fsetpos で使用。1

Polyspace 実装

このチェッカーは、無効なファイル位置をチェックします。

すべて展開する

問題

無効なファイル位置は、fsetpos() のファイル位置引数で使用する値が fgetpos() から取得したものではない場合に発生します。

リスク

関数 fgetpos(FILE *stream, fpos_t *pos) はストリームの現在のファイル位置を取得します。別の値を fsetpos(FILE *stream, const fpos_t *pos) のファイル位置引数として使用する場合、意図しないストリームの位置にアクセスする可能性があります。

修正方法

fgetpos() への正常な呼び出しから返された値を fsetpos() のファイル位置引数として使用します。

例 - memset() によるファイル位置引数の設定
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


FILE *func(FILE *file)
{
    fpos_t offset;
    if (file == NULL)
    {
        /* Handle error */
    }
    /* Store initial position in variable 'offset' */
    (void)memset(&offset, 0, sizeof(offset)); 

    /* Read data from file */

    /* Return to the initial position. offset was not
	returned from a call to fgetpos()	*/
    if (fsetpos(file, &offset) != 0)          
    {
        /* Handle error */
    }
    return file;
}
        
      

この例では、fsetpos()offset をファイル位置引数として使用しています。しかし、offset の値は memset() によって設定されています。上記のコードでは、ストリームの誤った位置にアクセスする可能性があります。

修正 — fgetpos() から返されるファイル位置を使用

fgetpos() を呼び出し、正常に値が返されたら、fsetpos() への呼び出しでその位置引数を使用します。

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

FILE *func(FILE *file)
{
    fpos_t offset;
    if (file == NULL)
    {
        /* Handle error */
    }
    /* Store initial position in variable 'offset' 
    using fgetpos() */
    if (fgetpos(file, &offset) != 0)         
    {
        /* Handle error */
    }

    /* Read data from file */

    /* Back to the initial position */
    if (fsetpos(file, &offset) != 0)          
    {
        /* Handle error */
    }
    return file;
}

チェック情報

決定可能性:決定不可能

バージョン履歴

R2019a で導入


1 Extracts from the standard "ISO/IEC TS 17961 Technical Specification - 2013-11-15" are reproduced with the agreement of AFNOR. Only the original and complete text of the standard, as published by AFNOR Editions - accessible via the website www.boutique.afnor.org - has normative value.