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

Compare with Current View Page History

« Previous Version 2 Next »

The fgets() function is typically used to read a newline-terminated line of input from a stream. The fgets() function takes a size parameter for the destination buffer and copies, at most, size-1 characters from a stream to a string. Truncation errors can occur if the programmer blindly assumes that the last character in the destination string will be a newline.

Non-Compliant Code Example

This non-compliant code example is intended to be used to remove the trailing newline (\n) from an input line.

char buf[1024];

fgets(buf, sizeof(buf), fp);
buf[strlen(buf) - 1] = '\0';

However, if the last character in buf is not a newline, it will truncate an otherwise-valid character.

Compliant Code Example

The following example uses strchr() to replace the newline character in the string only if it exists.

char buf[1024];

if (fgets(buf, sizeof(buf), fp))
{
  char *p;
  if (p=strchr(buf, '\n'))
    *p = 0;
}

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP01-A

1 (low)

1 (unlikely)

3 (low)

P3

P3

References

  • No labels