I'm developing a C function to read a single line from a text file, split it into tokens using strtok, and assign each token to specific fields in a struct. However, I'm encountering a segmentation fault when copying one of the tokens to a struct field using strcpy. Here's the code:
void readEnregFromTextFile(char *fileName, Tenreg *buffer) {
char string[256]; // Buffer to hold a line from the file
char *delimiters = ",|;\n";
FILE *f = fopen(fileName, "r");
if (f == NULL) {
printf("Error opening file\n");
return;
}
if (fgets(string, sizeof(string), f) != NULL) {
char *token = strtok(string, delimiters);
if (token != NULL) {
strcpy(buffer->name, token); // Copy first token to name
token = strtok(NULL, delimiters);
if (token != NULL) {
strcpy(buffer->departement, token); // Error occurs here
token = strtok(NULL, delimiters);
if (token != NULL) {
buffer->salary = atof(token);
}
}
}
} else {
printf("Error reading from file\n");
}
fclose(f);
}
the buffer structure is :
typedef struct {
char *name ;
char *departement ;
float salary ;
}
*the buffer is not allocated , it is just passed as a pointer so it's value can be modified , it is declared in the main as Buffer buffer
Issue When the function executes strcpy(buffer->departement, token);, I encounter a segmentation fault. After debugging, I found that the error occurs specifically at this line in the C code. The assembly output shows the error in the line:
mov 0xb8(%rbp),%rax
here is the call in the main for my function
Buffer buffer .
readEnregFromTextFile ("employee_data" , &buffer) ;
I attempted to replace strcpy with strdup, and the function worked without issues. However, I'd like to understand why strcpy is causing a segmentation fault and whether there's a fundamental issue with my code structure.
Question Why does strcpy cause a segmentation fault in this case, while strdup works? How should I correctly handle token assignment in this situation? Any insights would be appreciated!
Using my crystal ball:
If strdup
works and strcpy
doesn't it means that the buffer->departement
is:
NULL
, wild or not initalized pointer.strdup
allocates new memory and returns a pointer to that memory.
The remedy: