I have a string: "This is a simple string"
My objective is to find (with strstr
) "simple" and replace it with "sample".
CODE:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
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);
}
if((pch=malloc(BUFSIZ))==NULL){
printf("\n\t MEMORY ERROR");
exit(1);
}
str="This is a simple string ";
pch=str;
while(str[i]!='\0'){
printf("%c",str[i]);
i++;
}
printf(" -1break\n");
while((*pch!='\0')){
printf("%c",*pch);
pch++;
}
printf(" -2break\n");
printf("%s %d %d %d %d\n",str,strlen(str),sizeof(*str),BUFSIZ,(BUFSIZ-strlen(str)));/*OK*/
if((pch=strstr(str,"simple"))!=NULL){
printf("%s \n",pch); **/*OK*/**
while((*pch!='\0')){
printf("%c",*pch);
pch++;
} **/*SEG FAULT*/**
strncpy(pch,"sample",6);
printf("OK\n");
}
printf("%s %d\n",str,strlen(str));
printf("\n");
return 0;
}
OUTPUT:
$ ./strstr
This is a simple string -1break
This is a simple string -2break
This is a simple string 24 1 8192 8168
simple string
Segmentation fault
$
PROBLEM:
Can't replace "simple" with "sample".
QUESTION:
If pch
points correctly to 's' of "simple" why cant strncpy
replace the 6 letters of "sample"?