Search code examples
cloopssegmentation-faultgetline

Segmentation fault when using getline() in a loop


My code creates an array of 3 strings and attemps to populate each string using getline(). It also prints every string it gets:

int i;
size_t n = 100;
char (*words[3])[100];
for ( i = 0; i < 3; i++)
{
    getline(&words[i], &n, stdin);
    printf("%s\n",words[i] );
}    

When I enter the third string in the command line I get a segmentation error.
What's more, if I replace 3 with 5, I get the segmentation fault when I enter the first string.

So 1) How can I get the program to store all 3 or 5 or whatever strings I give it?, and
2) Why if I replace 3 with 5 I get the error on the first string?


Solution

  • You have to declare words as an array of pointer and initialize it to NULL according to the man page:

    char *words[3] = {NULL};
    

    http://ideone.com/GxV9qy