28 November 2007

Some experience with C string operation

Bad :
char buf[10];
scanf("%s", buf);

Good way:
char buf[10];
scanf("%9s", buf);


Bad :
char buf[BUFSIZ];
gets(buf);

Good way:
char buf[BUFSIZ];
int ch;
char *p;

if (fgets(buf, sizeof(buf), stdin)) {
/* fgets succeeds, scan for newline character */
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
else {
/* newline not found, flush stdin to end of line */
while (((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin) );
}
}
else {
/* fgets failed, handle error */
}

OR:

char buf[BUFSIZ];

if (gets_s(buf, BUFSIZ) == NULL) {
/* handle error */
}



Bad

char buf[BUFSIZ], *p;
int ch;
p = buf;
while ( ((ch = getchar()) != '\n') && !feof(stdin) && !ferror(stdin)) {
*p++ = ch;
}


*p++ = 0;


Good way

unsigned char buf[BUFSIZ];
int ch;
int index = 0;
int chars_read = 0;
while ( ( (ch = getchar()) != '\n') && !feof(stdin) && !ferror(stderr) ) {
if (index < class="code-object">char)ch;
}
chars_read++;
} /* end while */
buf[index] = '\0'; /* terminate NTBS */
if (feof(stdin)) {
/* handle EOF */
}
if (ferror(stdin)) {
/* handle error */
}
if (chars_read > index) {
/* handle truncation */
}


Reference:

https://www.securecoding.cert.org/confluence/display/seccode/FIO43-C.+Do+not+copy+data+from+an+unbounded+source+to+a+fixed-length+array