...
| Code Block | ||
|---|---|---|
| ||
void do_stuff(void) {
FILE *logfile = fopen("log", "a");
if (logfile == NULL) {
/* Handle error */
}
/* Write logs pertaining to do_stuff() */
fprintf(logfile, "do_stuff\n");
/* ... */
}
int main(void) {
FILE *logfile = fopen("log", "a");
if (logfile == NULL) {
/* Handle error */
}
/* Write logs pertaining to main() */
fprintf(logfile, "main\n");
do_stuff();
/* ... */
return 0;
}
|
However, the file log is opened twice simultaneously. The result is implementation-defined and potentially dangerous.
Implementation Details
On a Linux machine running gcc 4.3.2, this program produces the following output:
| Code Block |
|---|
do_stuff
main
|
which does not indicate the order in which data was logged.
Compliant Solution
In this compliant solution, a reference to the file pointer is passed as an argument to functions that need to perform operations on that file. This eliminates the need to open the same file multiple times.
| Code Block | ||
|---|---|---|
| ||
void do_stuff(FILE *logfile) {
/* Write logs pertaining to do_stuff() */
fprintf(logfile, "do_stuff\n");
/* ... */
}
int main(void) {
FILE *logfile = fopen("log", "a");
if (logfile == NULL) {
/* Handle error */
}
/* Write logs pertaining to main() */
fprintf(logfile, "main\n");
do_stuff(logfile);
/* ... */
return 0;
}
|
Implementation Details
On a Linux machine running gcc 4.3.2, this program produces the following output:
| Code Block |
|---|
main
do_stuff
|
which matches the order in which logging occurred.
Risk Assessment
Simultaneously opening a file multiple times can result in abnormal program termination or data integrity violations.
...