Segmentation fault?
Dave P. Schaumann
dave at cs.arizona.edu
Mon Feb 25 12:36:55 AEST 1991
In article <38192 at netnews.upenn.edu> widyono at eniac.seas.upenn.edu (Aasmodeus) writes:
>int getline(FILE *fp, char *line); /* decl. should it be line[]? */
>
>main(int argc, char *argv[])
>{
> char line[BUFSIZ]; /* line of input */
> while (getline(fp, line) > 0) {
> printf("%s\n", *line);
This is it ---------^ line is an array. *line is the first character of that
array. When printf sees "%s", it takes whatever the second parameter is, and
tries to indirect through it. You can get the same effect by saying
char c = 'x' ; *c = 'y' ;
A computer that has any kind of memory protection will almost certainly have
a segmentation fault at this point.
> if (fgets(line, BUFSIZ, fp) == NULL)
Here is another, more subtle bug. fgets will write up to BUFSIZ characters
(in this call) to line. This is not including the final '\0' character.
The best thing to do is declare char line[BUFSIZ + 1], and all will be well.
--
Dave Schaumann | Is this question undecidable?
dave at cs.arizona.edu |
More information about the Comp.unix.programmer
mailing list