0

For some reason this code is segfaulting for a reason I can't find out.

char *read_line(FILE *fp)
{
    char *out;
    int counter = 0;
    char c = getc(fp);

    while (c != '\n' && c != EOF)
    {
        *(out + counter) = c;
        counter++;
        c = getc(fp);
    }

    if (c == EOF || feof(fp))
    {
        return NULL;
    }

    *(out + counter) = '\0';
    return out;
}

I have already tried running it in gdb, and that has told me that the segfault is at *(out + counter) = c;. I can't figure out what I am doing wrong, can anyone else?

selbie
  • 100,020
  • 15
  • 103
  • 173
AppleDash
  • 1,544
  • 2
  • 13
  • 27
  • 5
    seems char * out is not initialized? – Jerry_Y Feb 09 '14 at 10:40
  • What would I initialize it to? O.o – AppleDash Feb 09 '14 at 10:42
  • If you want to read data to somewhere you need to provide the memory to do so. As the code currently stands `out` is just apointer to nowhere. And writing to where it points to provokes undefined behaviour and a crash. – alk Feb 09 '14 at 10:44
  • I understand how pointers work, but I don't see why this doesn't work. What confuses me is how this usually works, but sometimes it decides to segfault for no good reason. – AppleDash Feb 09 '14 at 10:45

1 Answers1

6

You're not assigning any value to out, so it's probably pointing to some invalid memory address.

What you probably want to do is find the length of the data first, then allocating the required amount of memory, and then read the actual data into the allocated memory:

char *out;
int counter = 0;
char c = getc(fp);
while (c != '\n' && c != EOF) {
    counter++;
    c = getc(fp);
}

out = malloc(counter+1);
fseek(fp,0,SEEK_SET);

counter = 0;
c = getc(fp);
while (c != '\n' && c != EOF) {
    *(out + counter) = c;
    counter++;
    c = getc(fp);
}
*(out + counter) = 0;

And don't forget to free(out) when you're done using it...

BTW, instead of the second for loop, you could simply use fgets(out,count,fp).

barak manos
  • 29,648
  • 10
  • 62
  • 114