c++ - Same strings in array have same memory address -


Why is the same string in a four * array the same address?

Is this compiler due to optimization?

Example:

  #include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; #include & lt; String.h & gt; #define ARR_SIZE 7 int main (int argc, char ** argv) {size_t i = 0, j = 0; Char * myArr [ARR_SIZE] = {, "it Engie is", "it is Engie" "third string" "This is the second string" "This is the first string", "This is the fifth string", "it is Inji "}; The {(j = i + 1; j & LT; ARR_SIZE; ++ j) (; I & lt; ARR_SIZE ++ i {for = 0) if (memcmp ((myArr + i), (myArr + J), Sizeof (char *)) == 0) {fprintf (stdout, "% p,% p \ n", * (myArr + i), * (myArr + j)); Fprintf (stdout, "This Start Index Started:% lu, Search Index:% lu \ n", i, j); }} 0 return 0; }  

GDB:

  (gdb) x / 7w myArr 0x7fffffffdd10: u "\ x4007a8" 0x7fffffffdd18: U "\ x4007c1" 0x7fffffffdd20: U "\ X4007db "0x7fffffffdd28: U" \ x4007e9 "0x7ffffffdddd30: U" \ x4007db "0x7fffffffdd38: U" \ x400802 "0x7fffffffdd40: U" \ x4007db "(gdb) x / 7s * myArr 0x4007a8:" This is the first string "0x4007c1:" This second string "0x4007db:" it Engie that "0x4007e9:" this is the third string "0x400802:" this is the fifth string "0x40081b:"% p,% p \ n "0x400823:" " 

It is called continuous merge. It is enabled at a high level of optimization, usually the compiler takes only all the unique stable values ​​and crashes them down. Good for memory usage and cache efficiency.

GCC is -fmerge- constant or -o and company

or it can not be used by other compilers. This compiler is specific

After implementing it I can imagine all C ++ compilers doing this is about the easiest optimization campaign

A perfect example of this Why is it?

  1. You can not make assumptions about where a steady value reside (undefined behavior)
  2. You should not change in constant prices (undefined behavior)

But we see many questions about people (not themselves) that they are away with modifying a certain string went.


Comments

Popular posts from this blog

winforms - C# Form - Property Change -

java - Algorithm negotiation fail SSH in Jenkins -

java - Messages from .properties file do not display UTF-8 characters -