1

I have a bit of code that I'll show here

// open file
FILE *file = fopen(filename, "rb");

// create buffer & lines array
char buffer[512];
char *lines[512];

// create index
int length = 0;
while (fgets(buffer, sizeof(buffer), file))
{
    // update & test
    lines[length] = buffer;
    printf("(1) %s", lines[length]);

    // ++
    length++;
}

// print nl separator
printf("\n");

// output
for (int i = 0; i < length; i++)
    printf("%s\n", lines[i]);

The output in the console is this:

(1) line 1
(1) line 2
(1) line 3
line 3
line 3
line 3

Even though I'm not overwriting anything in the second loop. Why is it doing this, and how can I solve this?

  • 2
    What do you mean "I'm not overwriting anything"? Every iteration overwrites `buffer` – William Pursell Aug 08 '22 at 16:34
  • 2
    All the `lines[]` elements point to the exact same buffer. – Ian Abbott Aug 08 '22 at 16:34
  • 2
    `lines[length] = buffer;` : this stores the same buffer address over and over. So all pointers of `lines` point to the exact same buffer. – Jabberwocky Aug 08 '22 at 16:34
  • Your're looking for [`strdup`](https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c) – Jabberwocky Aug 08 '22 at 16:36
  • @WilliamPursell yes I'm updating the lines string array, and setting that index to the buffer, and then adding to the `length` integer. –  Aug 08 '22 at 16:40
  • @Jabberwocky How would I get around this? Any memory copy method from the string library seg faults. –  Aug 08 '22 at 16:43
  • Your code is the same as: `for( int i = 0; i < 512; i += 1 ){ lines[i] = buffer; } while( fgets(buffer, sizeof buffer, file) ){ printf("(1) %s", lines[length]); length += 1; }`. Does that clarify? – William Pursell Aug 08 '22 at 16:44
  • 1
    If `strdup` is causing a segfault, then you have other issues. The most obvious possibility here is that you are reading more than 512 lines, but there are many possible issues. We'd need to see the code in which you are using `strdup`. – William Pursell Aug 08 '22 at 16:46
  • Yeah I got it now. I forgot to try strdup and was using strcpy/memcpy. Thank you all! –  Aug 08 '22 at 16:49

0 Answers0