Search code examples
cfgetsdouble-pointer

Value inside a double pointer isn't updated correctly (C)


I have a function that reads an input file and is supposed to modify the contents of a char** and a int*. The function is as follows:

void
input_parser(arguments* args, char** input, int* files) {
   char buffer[MAX];
   FILE *fr;
   fr = fopen(args->file,"r");
   if (fr == NULL) {
       printf("No correct input file was entered\n");
       exit(0);
   } 
   while(fgets(buffer,MAX,fr) != NULL) {
       input[*files] = strtok(buffer,"\n");
       (*files)++;
   }
   fclose(fr);
   return;
}

I have defined input and files as follows in the main program:

char* input[25];
files = 0;

I call the function as follows:

input_parser(args, input, &files);

The input file contains 3 lines as follows:

output1.xml
output2.xml
output3.xml

I notice that during the while loop the 'current' value is read correctly but stored in all input[*] resulting in:

input[0] = output3.xml
input[1] = output3.xml
input[2] = output3.xml

I would greatly appreciate if someone has any idea what is going wrong here.


Solution

  • The function is storing the address of the local variable buffer to each element in the input array: you need to copy the value returned by strtok(). The code as it stands is undefined behaviour as the buffer is out of scope once input_parser() returns, even it was not the logic is incorrect anyway.

    If you have strdup(), you just use it:

    input[*files] = strdup(strtok(buffer,"\n")); /* NULL check omitted. */
    

    otherwise malloc() and strcpy(). Remember to free() the elements of input when no longer required.

    Initialise input to be able determine which elements point to valid strings:

    char* input[25] = { NULL };