Main Content

ISO/IEC TS 17961 [xfilepos]

Using a value for fsetpos other than a value returned from fgetpos

Description

Rule Definition

Using a value for fsetpos other than a value returned from fgetpos.1

Polyspace Implementation

This checker checks for Invalid file position.

Examples

expand all

Issue

Invalid file position occurs when the file position argument of fsetpos() uses a value that is not obtained from fgetpos().

Risk

The function fgetpos(FILE *stream, fpos_t *pos) gets the current file position of the stream. When you use any other value as the file position argument of fsetpos(FILE *stream, const fpos_t *pos), you might access an unintended location in the stream.

Fix

Use the value returned from a successful call to fgetpos() as the file position argument of fsetpos().

Example - memset() Sets File Position Argument
#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;
}
        
      

In this example, fsetpos() uses offset as its file position argument. However, the value of offset is set by memset(). The preceding code might access the wrong location in the stream.

Correction — Use a File Position Returned From fgetpos()

Call fgetpos(), and if it returns successfully, use the position argument in your call to 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;
}

Check Information

Decidability: Undecidable

Version History

Introduced in 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.