Search code examples
carrayspointersvariable-length-array

Segfault when assigning token pointer (from strtok) to pointer element of 2d VLA of structs


I'm attempting to parse a csv file and store those values in an 2d VLA. The first codeblock shows the two calls I have to the function TokenizeLine which very simply uses strtok to break the line apart and assign the token to the appropriate cell in the array. The second block is the function in question.

  //Get first line of file then iterate through lines until
  //beginning comments are passed over
  fgets(currentLineStr, 8192, fileIn); 
  while (currentLineStr[0] == '#')
        fgets(currentLineStr, 8192, fileIn);

  //Start adding values to array. current line held by currentLineStr
  //is assigned first
  TokenizeLine(currentLineStr, eTable, yIndex, x, y);

  yIndex++;
  while(fgets(currentLineStr, 8192, fileIn) != NULL)
  {
        TokenizeLine(currentLineStr, eTable, yIndex, x, y);
        yIndex++;
  }

Within the following function I'm getting a segfault when assigning the token pointer to the pointer contained in the eTable struct.

void TokenizeLine(int x; int y; char currentLineStr[], Entry eTable[x][y], int yIndex, int x, int y)
{
  char *tokPtr;
  int xIndex = 0;

  tokPtr = strtok(currentLineStr, "|");
 *** eTable[xIndex][yIndex].str = tokPtr;*** (error happening here)

  while(tokPtr != NULL)
  {
        tokPtr = strtok(NULL, "|");
        eTable[xIndex][yIndex].str = tokPtr;
        //printf("%s\n", eTable[xIndex][yIndex].str);      

        xIndex++;
  } 
}

Been stuck on this for a while any/all input appreciated and encouraged.


Solution

  • You're not checking the return value of the first strtok() call.

    Also, in your while loop you check whether tokPtr is NULL, but then update it in the first line of the loop body before using it.

    You need remove the initial set of eTable[xIndex][yIndex].str, and move the second strtok() call to the end of the while loop:

      tokPtr = strtok(currentLineStr, "|");
    
      while(tokPtr != NULL)
      {
            eTable[xIndex][yIndex].str = tokPtr;
            //printf("%s\n", eTable[xIndex][yIndex].str);      
    
            tokPtr = strtok(NULL, "|");
            xIndex++;
      }