Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

If the file pointed to by new exists prior to a call to rename(), the behavior is implementation-defined. Therefore, care must be taken when using rename().

Non-Compliant Code Example

In the following non-compliant code, a file is renamed to another file using rename().

Code Block
bgColor#ffcccc"
/* program code */
char const *old = "oldfile.ext";
char const *new = "newfile.ext";
if(rename(old, new); != 0) {
  /* Handle rename failure */
}
/* program code */

However, if newfile.ext already existed, the result is undefined.

Compliant Solution

This compliant solution first checks for the existence of the new file before the call to rename(). Note that this code contains an unavoidable race condition between the call to fopen() and the call to rename().

Code Block
bgColor#ccccff"
/* program code */
char const *old = "oldfile.ext";
char const *new = "newfile.ext";

if (FILE *file = fopen(new, "r");

if (file !== NULL) {
  fclose(file);
  if(rename(old, new);) != 0) {
    /* Handle remove failure */
  }
}
else {
  /* handle error condition */
}
/* program code */

Note: There is a race condition inherent here!

Risk Analysis

Risk Assessment

Using rename() without caution leads to undefined behavior, possibly resulting in a file being unexpectedly overwritten.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO10-A

2 (medium)

3 (likely)

2 (medium)

P12

L2

References

Wiki Markup
\[[ISO/IEC 9899-1999:TC2|AA. C References#ISO/IEC 9899-1999TC2]\] Section 7.9.4.2, "The {{rename}} function"

...