2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
The standard C library includes a number of functions for handling streams. If not called correctly, these functions can have undefined behavior. More specifically:
* ``++FILE*++`` should be checked for null before being used in a function that accesses the file content
* The third argument of ``++fseek++`` must be ``++SEEK_SET++``, ``++SEEK_END++``, or ``++SEEK_CUR++``
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
FILE *file1 = fopen("myFile", "r");
fseek(file1, 1, SEEK_SET); // Noncompliant, file could be NULL
fclose(file1);
FILE *file2 = tmpfile();
ftell(file2); // Noncompliant, file could be NULL
if (file2) {
fseek(file2, 1, 3); // Noncompliant, third argument should either be SEEK_SET, SEEK_CUR or SEEK_END
}
fclose(file2);
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
FILE *file1 = fopen("myFile", "r");
if (file1) {
fseek(file1, 1, SEEK_SET);
fclose(file1);
}
FILE *file2 = tmpfile();
if (file2) {
ftell(file2);
fseek(file2, 1, SEEK_END);
fclose(file2);
}
----
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]