Why is the position of the line pointer different?

Why is the pointer line different every time I launch the application when I use StringBuilder, but the same when I declare a variable?

void Main()
{
    string str_01 = "my string";
    string str_02 = GetString();
    unsafe 
    {
        fixed (char* pointerToStr_01 = str_01)
        {
            fixed (char* pointerToStr_02 = str_02)
            {
                Console.WriteLine((Int64)pointerToStr_01);
                Console.WriteLine((Int64)pointerToStr_02);
            }
        }
    }
}

private string GetString()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("my string");

    return sb.ToString();
}

Conclusion:

40907812
178488268

next:

40907812
179023248

next:

40907812
178448964

+4
source share
4 answers

str_01contains a link to a constant string. StringBuilderhowever, it builds string instances dynamically, so the returned string instance is not essentially the same instance as a constant string with the same contents. System.Object.ReferenceEquals()will return false.

str_01 , , , , .

Edit:

" " UTF-8 .exe PE.Explorer . .data , , .

, str_01 , , , x64 Windows 8.1 (ASLR). - , , PE.

+12

, , , (, , ), # , . , , str_02 string.Intern.

+1

,
str_01 ,

fixed (char* pointerToStr_01 = str_01)


fixed (char* pointerToStr_02 = str_02)

, ,

, ,

.
+1

,

 Console.WriteLine((Int64)pointerToStr_01);

- , , .

:

  • str_01 = " ", , , , , String (.. ) " " . Fixed , , , .
  • , StringBuilder.

:

 string str_01 = GetString();
 private static string GetString()
    {
        var sb = new String(new char[] {'m','y',' ','s','t','r','i','n','g'});
        return sb;
    }
0

Source: https://habr.com/ru/post/1570321/


All Articles