1

I was checking direct comparison between strings using == operator. When both string is character pointer that it compare correctly. Sooner I realize it happen compiler by default assign same address to both char pointer variable as they hold the same value.

#include<stdio.h>

void update(char *str2){
 *(str2+2)='O';
}
int main(){

char *str1="Sudhanshu";
char *str2="Sudhanshu";

printf(" %s  , %s ",str1,str2);
update(str2);
printf(" %s  , %s ",str1,str2);

if(str1==str2){
   printf("True\n");
}else
  printf("False\n");

return 0;
}

The address of str1 and str2 is the same. So I want to check whether updating one pointer actually affect other.

However, I'm getting a segmentation fault. Why am I getting a seg fault?

Alex K
  • 8,269
  • 9
  • 39
  • 57
Sudhanshu Patel
  • 759
  • 1
  • 5
  • 12
  • 2
    If two pointers are the same, updating the the information pointed by one pointer _will_ of course update the information pointed by the other pointer, provided the memory pointed by the said pointer is writeable which is not the case here ( see answer below). `str1` and `str2` point to the same location because the C compiler may optimize this as string literals are not writable. – Jabberwocky Jan 22 '18 at 10:01

1 Answers1

7

Trying to modify string literal is undefined behavior. String literals are read only - it's non modifiable.

Also don't try to explain undefined behavior. Here you have segmenattion fault trying to access the memory which is non-modifiable.

You can use strdup though

char *str1=strdup("Sudhanshu");
char *str2=strdup("Sudhanshu");

This will allow you to change the strings and also you need to free the memory that is allocated by strdup when you are done working with it.

strdup is a POSIX thing - in case you don't have that, use malloc strcpy combination to mimic the same behavior.

Also as got from comment Bart Friederichs that yes ofcourse you can declare an array of char and initialize them with the literal itself.

char str1[]="Sudhanshu";

The str1 is modifiable and also you don't need to free the memory explicitly in this case.


Even if you compare pointer to the same string literals - they may not point to the same memory location. This may vary. So you can't be sure that they will always results in comparison of two same value. This may vary compiler to compiler.

user2736738
  • 30,591
  • 5
  • 42
  • 56