Home > OS >  strcpy, assignment from strtok to a variable length struct string
strcpy, assignment from strtok to a variable length struct string

Time:02-21

typedef struct {
    long f1; 
    char f2[FIELD2_STRING_LENGTH];
    char* f3; 
} bankRecord;



while (fgets(line, 1000, file)) {
        record *rptr = malloc(sizeof(record));
        char *token = strtok(line, ",");
        rptr->f1 = atol(token); // works fine
        strcpy(rptr->f2,strtok(NULL, ",")) // works fine
        rptr->f3 = strtok(NULL, ","); // fails, at the end, all records have the same data in f3, if strcpy is used - causes segmentation fault
        records[i  ] = record; 
    }

The code is extracted from a csv file reader method. The csv file has the format "long integer, fixed Character string, variable Character String". records is an array of pointers to record objects (type record **). At the end of the while loop all the records seem to have the same value of f3 (the last one added) while correct values are stored for f1 and f2. I can't figure out what's causing this because both f2 and f3 are strings. Changing f3's assignment to strcpy from "=" causes segmentation fault.

CodePudding user response:

br->f3 = strtok(NULL, ","); 

sets a pointer to the internals of strtok. It doesnt copy the string. Basically all your f3 pointers point at the same location.

You need

br->f3 = strdup(strtok(NULL, ",")); 

to make a copy of the string at that point. You will need to free the memory later

  • Related