...
Code Block |
---|
|
#include <stdio.h>
#define BUFFER_SIZE 1024
void func(void) {
char buf[BUFFER_SIZE];
if (gets(buf) == NULL) {
/* Handle error */
}
} |
...
Code Block |
---|
|
#include <stdio.h>
enum { BUFFERSIZE = 32 };
void func(void) {
unsigned char buf[BUFFERSIZE];
int ch;
int index = 0;
int chars_read = 0;
while (((ch = getchar()) != '\n')
&& !feof(stdin)
&& !ferror(stderr)) {
if (index < sizeof(buf) - 1) {
buf[index++] = (unsigned char)ch;
}
chars_read++;
}
buf[index] = '\0'; /* Terminate NTBS */
if (feof(stdin)) {
/* Handle EOF */
}
if (ferror(stdin)) {
/* Handle error */
}
if (chars_read > index) {
/* Handle truncation */
}
}
|
...
Code Block |
---|
while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin)) |
Noncompliant Code Example (fscanf()
)
In this noncompliant example, the call to fscanf()
can result in a write outside the character array buf
.
Code Block |
---|
|
#include <stdio.h>
void get_data(void) {
enum { BUF_LENGTH = 1024 };
void get_data(void) {
char buf[BUF_LENGTH];
fscanf(stdin, "%s", buf); */
/* rest of function
}
|
Compliant Solution (fscanf()
)
In this compliant solution, the call to fscanf()
is constrained not to overflow buf
.
Code Block |
---|
|
#include <stdio.h>
void get_data(void) {
enum { BUF_LENGTH = 1024 };
void get_data(void) {
char buf[BUF_LENGTH];
fscanf(stdin, "%1024s", buf);
/* rest of function */
}
|
...