...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h> #include <string.h> #define BUFFER_SIZE 128 void func(void) { char buf[BUFFER_SIZEBUFSIZ]; if (fgets(buf, sizeof(buf), stdin) == NULL) { /* Handle error */ } buf[strlen(buf) - 1] = '\0'; /* discard newline */ } |
The strlen() function computes the length of a string by determining the number of characters that precede the terminating null character. A problem occurs if the first character read from the input by fgets() happens to be a null character. This may occur, for example, if a binary data file is read by the fgets() call [Lai 2006]. If the first character in buf is a null character, strlen(buf) returns 0 and a write-outside-array-bounds error occurs.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h> #include <string.h> #define BUFFER_SIZE 128 void func(void) { char buf[BUFFER_SIZEBUFSIZ]; char *p; if (fgets(buf, sizeof(buf), stdin)) { buf[BUFFER_SIZE - 1] = '\0'; p = strchr(buf, '\n'); if (p) { *p = '\0'; /* discard newline */ } } else { /* Handle error */ } } |
...