/* Reads an input file and prints the contents in all caps. The program terminates when it reads a period. A copy of the output is also stored in a string. Input that contains no periods results in an infinite loop ending in a segmentation fault. */ #include #include #include int main( void ) { // Prompt user input. printf( "Enter some characters.\n" ); // A char for storage. char c; // The program will run with a char array of predefined size because memory is allocated implicitly. // The program fails to execute using the char * because memory must be allocated explicitly when // using a pointer to represent and populate a string, unless a string literal is used. // To see the program run correctly, comment line 30 and uncomment line 27. // To see the program cause a segmentation fault, comment line 27 and uncomment line 30. // A char array to store the output, with no segmentation fault as long as the length of the input isn't too long. char str[ 30 ]; // A string to store the output, with a segmentation fault. //char *str; // Keep track of the length. This variable being declared after *str means that memory must be allocated // to the pointer if you want to build a string with it. Memory is allocated sequentially, so a segmentation // fault will result if you don't allocate any memory at line 30 above. int len = 0; // A pointer to use to populate the string. char *cp = str; // Read the input 1 char at a time. while( 1 ) { // The program quits when it sees a period. if ( ( c = getchar( ) ) == '.' ) { putchar( toupper( c ) ); *cp = toupper( c ); len++; break; } // Otherwise is echoes the char it read as upper case and reads the next one. The upper case char is also stored in a string. else { putchar( toupper( c ) ); *cp = toupper( c ); cp++; len++; } } // A newline char at the end of the output. putchar( '\n' ); return 0; }