Search code examples
csegmentation-faultdynamic-memory-allocationfreestrsep

Segmentation Fault using strsep reading a csv file


I'm currently trying to read a csv file using strsep but it never passes the first line

int main(){
    
    FILE *fp = fopen("users100.csv", "r");
    
    if(!fp){
        printf("Erro");
        return 0;
    }

    char *str;

    str = (char *) malloc(10240);


    while(fgets (str, 10240, fp) != NULL){
    
        char *tmp = strdup(str);
        char *token;
        char **sp = &str; 

        sp = &tmp;

        while(token = strsep(&str, ";")){
            
            printf("%s ", token);

        }

        putchar('\n');

    }

    free(str);

    fclose(fp);
    
    return 0;
}

The output of this program is

public_repos id followers follower_list type following_list public_gists created_at following login
 
Segmentation fault (core dumped)

It prints the first line but not the rest.

Thank you!


Solution

  • The problem is that in this call

    strsep(&str, ";")
    

    the pointer str is changed.

    For starters there is no great sense to reinitialize the pointer sp.

        char **sp = &str; 
    
        sp = &tmp;
    

    You should write

    char *pos = tmp;
    char **sp = &pos; 
    

    In this while loop you need to write

        while ( ( token = strsep( sp, ";" ) ) ){
            
            printf("%s ", token);
    
        }
    

    And then you need to free the both strings

    free( str );
    free( tmp );