CERT.FSETPOS.VALUE

Only values returned from the ‘fgetpos()’ function can be used as arguments for the ‘fsetpos()’ function.

The CERT.FSETPOS.VALUE checker flags cases where the 'fsetpos()' function is called by an argument of the type fpos_t that was not created by the 'fgetpos()' function.

Vulnerability and risk

Calling the 'fsetpos()' function with an argument of type fpos_t that was not created by the 'fgetpos()' function leads to undefined behavior.

Mitigation and prevention

Verify that the ‘fsetpos()’ function always uses position values that are returned from the ‘fgetpos()’ function.

Vulnerable code example

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

   int opener(FILE *file)
   {
       int rc;
       fpos_t offset;
       memset(&offset, 0, sizeof(offset));

      if (file == NULL) {
         return -1;
      }

      /* Read in data from file */
      fsetpos(file, &offset);
      if (rc != 0 ) {
          return rc;
      }
      return 0;
  }

In this noncompliant example, Klocwork reports a CERT.FSETPOS.VALUE defect on line 15, because the fsetpos() function is using the value ‘offset’ that was not created by the fgetpos() function.

Fixed code example

Copy
    #include <stdio.h>
    #include <string.h>
    int opener(FILE *file)
    {
        int rc;
        fpos_t offset;
        memset(&offset, 0, sizeof(offset));

        if (file == NULL) {
           return -1;
       }
       fgetpos(file, &offset);
       /* Read in data from file */
       fsetpos(file, &offset);
       if (rc != 0 ) {
           return rc;
       }

       return 0;
   }

The above code is compliant as the fsetpos() function uses the value ‘offset’ that was previously created by the fgetpos() function.