OiO.lk Blog C# Segmentation fault when copying tokens to struct fields using strcpy in C function with strtok
C#

Segmentation fault when copying tokens to struct fields using strcpy in C function with strtok


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);
}

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    

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!



You need to sign in to view this answers

Exit mobile version