prev up next   top/contents search

comp.lang.c FAQ list · Question 7.4

Q: I'm reading lines from a file into an array, with this code:

	char linebuf[80];
	char *lines[100];
	int i;

	for(i = 0; i < 100; i++) {
		char *p = fgets(linebuf, 80, fp);
		if(p == NULL) break;
		lines[i] = p;
	}
Why do all the lines end up containing copies of the last line?


A: You have only allocated memory for one line, linebuf. Each time you call fgets, the previous line is overwritten. fgets doesn't do any memory allocation: unless it reaches EOF (or encounters an error), the pointer it returns is the same pointer you handed it as its first argument (in this case, a pointer to your single linebuf array).

To make code like this work, you'll need to allocate memory for each line. See question 20.2 for an example.

References: K&R1 Sec. 7.8 p. 155
K&R2 Sec. 7.7 pp. 164-5
ISO Sec. 7.9.7.2
H&S Sec. 15.7 p. 356


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North