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

Compare with Current View Page History

« Previous Version 2 Next »

The strlen() function computes the length of a string. It returns the number of characters that precede the terminating NULL character. Errors can occur when assumptions are made about the type of data being passed to strlen(), e.g., in cases where binary data has been read from a file instead of textual data from a users's terminal.

Non-Compliant Code Example

This non-compliant code example is intended to be used to remove the trailing newline (\n) from an input line. The fgets() function is typically used to read a newline-terminated line of input from a stream, takes a size parameter for the destination buffer and copies, at most, size-1 characters from a stream to a string.

char buf[1024];

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

However, if the first character in buf is a NULL, strlen(buf) will return 0 and a write-outside-array-bounds error will occur.

Compliant Solution

This compliant solution checks to make sure the first character in the buf array is not a NULL and that the last character is indeed a newline before replacing it with a NULL.

char buf[1024];

if (fgets(buf, sizeof(buf), fp) != NULL) {
	if (buf[0] != '\0' && buf[strlen(buf) - 1] == '\n')
		buf[strlen(buf) - 1] = '\0';
}

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FI036-C

1 (low)

1 (unlikely)

3 (low)

P3

L3

References

  • No labels