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

1   #include <stdio.h>
2   #include <string.h>
3
4   int opener(FILE *file)
5   {
6       int rc;
7       fpos_t offset;
8       memset(&offset, 0, sizeof(offset));
9
10      if (file == NULL) {
11         return -1;
12      }
13
14      /* Read in data from file */
15      fsetpos(file, &offset);
16      if (rc != 0 ) {
17          return rc;
18      }
19      return 0;
20  }

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

1    #include <stdio.h>
2    #include <string.h>
3    int opener(FILE *file)
4    {
5        int rc;
6        fpos_t offset;
7        memset(&offset, 0, sizeof(offset));
8
9        if (file == NULL) {
10           return -1;
11       }
12       fgetpos(file, &offset);
13       /* Read in data from file */
14       fsetpos(file, &offset);
15       if (rc != 0 ) {
16           return rc;
17       }
18
19       return 0;
20   }

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

External guidance