C & C++

C & C++

Made by DeepSource

Using a copied object of FILE type might not have intended consequences CXX-C1002

Anti-pattern
Minor

The address associated with the FILE object (from stdio.h) is significant as it is used to control the IO stream. A by-value copy of the FILE object might result in unintended consequences like access violation. Such access violation could result in a crash, hence increasing the attack surface for denial-of-service attacks.

To avoid such issues, it is recommended that you avoid copying the FILE object. Instead of a by-value copy, consider using a by-reference variable as shown in the example below.

Bad practice

#include <stdio.h>

int main(void) {
  // new FILE object is copied here
  FILE newout = *stdout;
  // bug-prone usage of copy of a FILE object
  if (fputs("Hello, World!\n", &newout) == EOF) {
    return -1;
  }
  return 0;
}

Recommended

#include <stdio.h>

int main(void) {
  // reference to a FILE object is okay
  FILE *newout = stdout;
  if (fputs("Hello, World!\n", newout) == EOF) {
    return -1;
  }
  return 0;
}