Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the behaviour of this code undefined in C?

I've been given this code and I'm not quite sure why its behaviour is undefined. My guess is that it has something to do with the memory locations of the two strings and the location(s)' comparison in the if condition.

int main(void) { 
  char *str1 = "xyz"; 
  char *str2 = "xyz";

  if (str1 == str2) {
     printf("Same!\n");
  }  else {
     printf("Not Same!\n");
  }
  return 0; 
}
like image 534
starcodex Avatar asked Nov 21 '25 17:11

starcodex


2 Answers

It's unspecified (not undefined, there's a subtle distinction) as to whether identical string constants are folded to occupy the same memory.

C++11, 6.4.5 String literals /6 states:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

Both str1 and str2 are pointers to a block of memory containing the four characters { 'x', 'y', 'z', '\0'} and they are, by definition, non-modifiable.

That means the compiler is free to set both those variables to point to the same block of memory, for efficiency, if it so desires.

Hence str1 and str2 (I'm talking about the pointers, obviously the content behind the pointers is identical) may be identical or not.

like image 118
paxdiablo Avatar answered Nov 23 '25 07:11

paxdiablo


"xyz" is a string literal which is put in to "Read-only" section gets mapped into the process space as read-only (which is why you can't change it).

so both str1 and str2 are pointing to same address. This is the reason for printf("Same!\n"); got executed.

This is platform dependent. Refer String literals: Where do they go?

like image 25
Jeyaram Avatar answered Nov 23 '25 06:11

Jeyaram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!