I am trying to get each line from a file and doing some string operations. But my piece of code throws seg fault. I tested the same thing for one line as a different program and it works fine. But when I read from a file and do string manipulation operations it throws me segmentation fault.
Variable declarations:
char *pch3,str1[100],str2[100]
pch3 = strtok(line3,",");
while(pch3!=NULL)
{
if(strcmp(pch3,"?") == 0)
{
strcat(str1,"0");
strcat(str1,",");
}
else
{
strcat(str1,pch3);
strcat(str1,",");
}
pch3 = strtok(NULL,",");
}
strlen1=strlen(str1);
memcpy(str2,str1,strlen1-1);
fp2=fopen("breast-cancer-wisconsin-miscellaneous-cleansed.data","a");
fprintf(fp2,"%s\n",str2);
fclose(fp2);
You do not initialize
str1andstr2, which means when you usestrcatit tries to find the end of the previous string, but that can be anywhere instr1, even outsidestr1ifstr1does not contain a zero.Change the declaration to this and it should work better: