Main Content

Invalid file position

fsetpos() is invoked with a file position argument not obtained from fgetpos()

Description

This defect 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().

Examples

expand all

#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;
}

Result Information

Group: Programming
Language: C | C++
Default: Off
Command-Line Syntax: INVALID_FILE_POS
Impact: Medium

Version History

Introduced in R2017b