Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 10 Next »

The rename() function has the following prototype:

int rename(const char *old, const char *new);

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().
/* program code */
const char *old = "oldfile.ext";
const char *new = "newfile.ext";
if (rename(old, new) != 0)

Unknown macro: { /* Handle rename failure */}/* program code */{null}

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().
/* program code */
const char *old = "oldfile.ext";
const char *new = "newfile.ext";
FILE *file = fopen(new, "r");

if (file != NULL) {
if (rename(old, new) != 0)

Unknown macro: { /* Handle remove failure */ }


Unknown macro: { /* handle error condition */}/* program code */{null}

Risk Assessment

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




Remediation Cost




2 (medium)

2 (probable)

2 (medium)



Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.


[[ISO/IEC 9899-1999]] Section, "The rename function"

  • No labels