/* * no_crash.c * * use fgets rather than scanf for reading strings * */ #include #include // remove trailing newline, if there is one void trim(char string[]){ int length = strlen(string); // printf(" trim: length of the string is %d\n", length); // printf(" trim: first char is '%c'\n'", string[0]); // printf(" trim: the last char is '%c'\n", string[length-1]); if (string[length-1] == '\n'){ string[length-1] = (char) 0; } } // read in a string, and then print it back. void echo(){ char buffer[8]; printf("Type something: "); // scanf("%s", buffer); // Will overflow if > 8 chars. fgets(buffer, 8, stdin); // This one can't overflow. trim(buffer); // remove trailing newline, if present printf("You said: '%s'\n\n", buffer); } int main(){ int i; for (i=0; i<10; i++){ echo(); } return 0; }