Why is the behaviour of this code undefined in C?
c, undefined-behavior
Solution
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.
Problem
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; } ```