As summary your str
pointer should point to a read/write memory area like memory allocated with malloc
/calloc
/realloc
or static char array like char str[50]
or char str[] = "simple string";
char *str = "simple string"
, str
here is pointing to a literal string. And literal strings are stored in read only memory area so you can not edit it
Code critics:
1) first the following line is wrong
str="This is a simple string ";
you have allocated a memory for str and then you have not use it you have changed the pointer. The pointer now is pointing to a literal string (constant string) instead of its orgin memory area (allocated with malloc). it should be:
strcpy(str,"This is a simple string ");
the same for
pch = str;
pch
is pointing to the same literal string of str
and
pch=strstr(str,"simple")
pch
also here is pointing to a literal string because str
is a literal sting
2) the following line is wrong
strncpy(pch,"sample",6);
pch
is pointing to literal string and copy to a pointer pointing to literal string is undefined behaviour and this cause a crash
Code fixed:
int main (int argc, char *argv[]){
char *str;
char *pch;
int i=0;
if((str=malloc(BUFSIZ))==NULL){
printf("\n\t MEMORY ERROR");
exit(1);
}
strcpy (str, "This is a simple string ");
if((pch=strstr(str,"simple"))!=NULL) {
strncpy(pch,"sample",6);
}
printf("%s\n", str);
}