'strcpy, assignment from strtok to a variable length struct string
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
