cstrchr

strchr function keep giving me core dumped error


I am trying to write code that copy and print the word in text file on the screen with getline() and strchr() functions. so this is my code:

void read_teams(char* text)
{
    FILE *fp=fopen(text,"r");
    char* tname=NULL;
    size_t tname_size=0;
    while(getline(&tname,&tname_size,fp)!=EOF)
    {
        tname[strchr(tname,'\n')-tname]='\0';
        printf("%s\n",tname);
    }
    fclose(fp);
}

when it is read strchr function it's show:

Segmentation fault (core dumped)

so why? i have to use this function with getline ,so don't tell me to write my code in other way please.


Solution

  • If the buffer does not contain a \n character, then strchr()-tname will be way before tname. That will cause a seg fault. So use:

    while(getline(&tname,&tname_size,fp)!=EOF)
    {
        char *p= strchr(tname,'\n');
        if (p)
            tname[p-tname]='\0';
        printf("%s\n",tname);
    }