0

Im currently teaching myself c, and during exercising pointers use I bumped into this problem- I'm trying to replace a substring in a string that is pointed to (meaning,not a char array), with a substring from another pointed string.

char *str1="I like pizza!";
char *str2="love";

    printf("%s\n", str1);

for (int i=2, j=0; j<4; i++, j++) { 
    *(str1+i)=*(str2+j); 
}

    printf("%s\n", str1);

Result should be- the way I see it- output of "I like pizza", followed by output of "I love pizza". Instead, I get a segfault (error 139). I scraped the web for a solution but couldn't find what is the problem.

(I am aware that the for loop is not perfect, to say the least, but that's not the issue here). Please help me out :)

Benson
  • 1
  • 1

2 Answers2

0

Because those are pointers to a read-only part in you're program's binary. You can't change the content. Try this instead:

char str1[] = "I like pizza!";
char str2[] = "love"; // actually, this one can stay as a pointer as we're only reading

Now the strings are copied to the stack and the program works as intended.

Blaze
  • 16,736
  • 2
  • 25
  • 44
0

The strings pointed to by str1 and str2 are read-only.

The behaviour on attempting to change their contents is undefined.

Use char str1[] = "I like pizza!"; &c. instead, which copies the read-only string to str1[], which you are then free to modify.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483