Question

I have a string and I use strtok to parse it.

I then want to use strstr on the pointer from strtok but I keep getting a seg fault.

Any thoughts on why?

char *pch,*pch1,*pch2,*pch3,

pch=strstr(line1,key);

            if(pch!=NULL){
                pch1=strstr(line1,key1);
                pch2=strstr(line1,key2);
                pch3=strstr(line1,key3);

                if(pch1!=NULL && pch2!=NULL && pch3!=NULL){
                    printf("%s",line1);   
                    sym++;

                    pch2=strtok(line1," ");

                    while(pch2!=NULL){
                        pch2=strtok(NULL," ");
                        pch3=strstr(pch2,key1);
                        printf("%s\n",pch3);


                    }
                }
            }
Was it helpful?

Solution

pch2=strtok(NULL," ");
pch3=strstr(pch2,key1);

You don't check pch2 != NULL before calling strstr. It is after all bound to happen since it's the only way you'll get out of that loop.

How about:

while((pch2 = strtok(NULL," "))) {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top