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 read. These assumptions may be violated, for example, when binary data has been read from a file instead of textual data text from a user's terminal.
Non-Compliant Code Example
This non-compliant code example is intended to be used attempts 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. It takes a size parameter for the destination buffer and copies, at most, size-1 characters from a stream to a string.
| Code Block | ||
|---|---|---|
| ||
char buf[BUFSIZ + 1];
if (fgets(buf, sizeof(buf), fp) == NULL) {
/* handle error */
}
buf[strlen(buf) - 1] = '\0';
|
However, if The strlen() function computes the length of a string by determining the number of characters that precede the terminating null character. If the first character in buf is a null character, 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 before modifying it based on the results of strlen(uses strchr() to replace the newline character in the string, if it exists (see FIO36-C. Do not assume a newline character is read when using fgets()).
| Code Block | ||
|---|---|---|
| ||
char buf[BUFSIZ + 1];
char *p;
if (fgets(buf, sizeof(buf), fp)) {
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
}
else {
/* handle error condition */
}
|
...