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?

✍: Guest

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.

2015-11-13, 1156👍, 0💬