I recently recommended K&R to a friend who wanted to learn C. He came across an exercise in the first chapter that gave him various errors. I compiled it on my Ubuntu installation, alternating between the C90 option and the defaults. I've looked at every angle but it seems to be perfect code...yet it consistently gives me a segmentation fault each time I run it. I'm not the sharpest programmer in the shed but this has me pretty frustrated.
What on earth is causing such an error?
Here is the code:
#include <stdio.h>
#define MAXLINE 1000
void reverse(char s[]);
/* A program that reverses its input a line at a time */
main()
{
int c, i;
char line[MAXLINE];
for (i = 0; (c = getchar()) != EOF; ++i) {
line[i] = c;
if (c == '\n') { /* Upon encountering a newline */
line[i] = '\0'; /* replace newline with null terminator */
i = 0;
reverse(line);
printf("\n%s\n", line);
}
}
return 0;
}
/* A function that reverses the character string */
void reverse(char s[])
{
int a, z;
char x;
for (z = 0; s[z]; ++z) /* Figure out where null terminator is */
;
--z;
for (a = 0; a != z; ++a) { /* Reverse array usinng x as placeholder */
x = s[a];
s[a] = s[z];
s[z] = x;
--z;
}
}