0

I have some doubts about string literals.

Firstly, I know that C-strings must be compared using the strcmp(),strncmp() or some other function and if one uses ==, then they compare the pointers as the array name "decays" into a pointer to its first element.
Is there a chance that two same strings can have the same address,i.e, Can these conditions be true?

if("string"=="string")

/*OR*/

char* str="string";
if(str=="string")

/*OR*/

char* str="string";
char* str2="string";
if(str==str2)


Secondly, Can two unequal strings contain the same address?

Lastly, Do these strings stay in read only memory segment until the program ends?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
  • My answer [here](http://stackoverflow.com/a/26279717/1708801) covers a lot of this ground. – Shafik Yaghmour Feb 11 '15 at 14:11
  • @CoolGuy Yes all 3 of your examples are typically true because a compiler will see that the string literals are equal and because it trusts that the programmer will not try to modify them which also answers your last question (if you want to modify a string then use char-array instead of string literal). – Bernd Elkemann Feb 11 '15 at 14:20
  • @ShafikYaghmour , Thanks. That answered my first two questions. What about the 3rd one? Do these read only strings exist as long as the program does or will the memory be sent back to the OS once there aren't any pointers pointing to the string? – Spikatrix Feb 11 '15 at 15:00
  • @CoolGuy yes, they have static storage duration so they will exist until the program ends. – Shafik Yaghmour Feb 11 '15 at 15:01
  • @eznme , That wasn't my question... I should've bolded the "until the program ends" part. – Spikatrix Feb 11 '15 at 15:01
  • @ShafikYaghmour ,Thanks once again. You've cleared all my doubts on this. – Spikatrix Feb 11 '15 at 15:13

0 Answers0