Versions Compared

Key

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

...

Function

Preferable
Alternative

Comments

atof

strtod

No error indication, undefined behavior on error.

atoi

strtol

No error indication, undefined behavior on error.

atol

strtol

No error indication, undefined behavior on error.

atoll

strtoll

No error indication, undefined behavior on error.

rewind

fseek

No error indication, silent failure on error.

setbuf

setvbuf

No error indication, silent failure on error.

Noncompliant Code Example (atoi())

...

  • do not need to set errno on an error.
  • have undefined behavior if the value of the result cannot be represented. (See undefined behavior 119 of Annex J of C11the C Standard.)
  • return 0 if the string does not represent an integer (which is indistinguishable from a correctly formatted, zero-denoting input string), but the C Standard only specifies the behavior of these functions on success.

...

Code Block
bgColor#ffcccc
langc
char *file_name;
FILE *fp;

/* initializeInitialize file_name */

fp = fopen(file_name, "r");
if (fp == NULL) {
  /* Handle open error */
}

/* readRead data */

rewind(fp);

/* continueContinue */

It is impossible to determine if rewind() succeeded.

...

Code Block
bgColor#ccccff
langc
char *file_name;
FILE *fp;

/* initializeInitialize file_name */

fp = fopen(file_name, "r");
if (fp == NULL) {
  /* Handle open error */
}

/* readRead data */

if (fseek(fp, 0L, SEEK_SET) != 0) {
  /* Handle repositioning error */
}

/* continueContinue */

Both the noncompliant code example and the compliant solution are taken from FIO07-C. Prefer fseek() to rewind().

...

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

Related Guidelines

ISO/IEC 9899:2011 Section 7.21.5.5, "The setbuf function," Section 7.21.6.7, "The sscanf function," Section 7.21.9.2, "The fseek function," 7.21.9.5, "The rewind function," Section 7.22.1.2, "The atoi, atol, and atoll functions," and Section 7.22.1.4, "The strtol, strtoll, strtoul, and strtoull functions"

...

MITRE CWECWE-20, Insufficient input validation
CWE-676,

...

Use of potentially dangerous function

...

MITRE CWE: CWE-20, "Insufficient input validation"

Bibliography

[Klein 2002]"Bullet Proof Integer Input Using strtol()

...