Interview Questions

Why do all the lines end up containing copies of the last line?

C Interview Questions and Answers


(Continued from previous question...)

Why do all the lines end up containing copies of the last line?

Q: I'm using fgets to read lines from a file into an array of pointers. 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.

(Continued on next question...)

Other Interview Questions