Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string pointer position is different?

Why string pointer position is different each time I ran the application, when I'm using StringBuilder but 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();
}

Output:

40907812
178488268

next time:

40907812
179023248

next time:

40907812
178448964

like image 544
Mohamad Shiralizadeh Avatar asked Dec 08 '22 05:12

Mohamad Shiralizadeh


1 Answers

str_01 holds a reference to constant string. StringBuilder however builds string instances dynamically, so the returned string instance is not referentially the same instance as the constant string with the same content. System.Object.ReferenceEquals() will return false.

Since the str_01 is a reference to a constant string, its data is probably stored in a data section of the executable, which always gets the same address in the application virtual address space.

Edit:

You can see the "my string" text in UTF-8 encoding when you open the compiled .exe file using PE.Explorer or similar software. It is present in the .data section of the file, including a preferred Virtual Address where the section should be loaded in process virtual memory.

I have however not been able to reproduce that str_01 has a same address on multiple runs of the application, probably because my x64 Windows 8.1 performs Address space layout randomization (ASLR). Because of that, all pointers will be different across multiple runs of the application, even those that point directly to loaded PE sections.

like image 158
YourSelf Avatar answered Jan 08 '23 06:01

YourSelf