String interning, pointers and a dangerous side-effect

The CLR interns managed strings – this means that if the same string is used multiple times, all of them refer to the same instance of the string. This is possible because System::String is immutable – so the moment you change one of those strings, you are actually changing the reference which now refers to the new string (quite possibly another interned string). All this is fine as long as the strings are immutable. But, sometimes you can remove their immutability – when you use interior or pinning pointers to directly access the underlying character array. See the following code snippet :-

String^ s1 = "hello";
String^ s2 = "hello";

interior_ptr<Char> p1 = const_cast<interior_ptr<Char> >(
    PtrToStringChars(s1));
interior_ptr<Char> p2 = const_cast<interior_ptr<Char> >(
    PtrToStringChars(s2));

//modifying s2 through interior pointer p2
for(; *p2; *p2++='a');

//s1 and s2 are both "aaaaa"
Console::WriteLine("{0} and {1}",s1,s2);

We changed string s2 using the interior pointer p2, but because s2 and s1 are interned to the same string instance, we inadvertently change both the strings – s1 and s2. Nasty huh? Just for your information, string interning is done across AppDomains, so you might be changing strings all over the place and it might be a tough bug to figure out. So remember, when you play with strings using interior or pinned pointers, be careful, really careful.

Advertisements

13 thoughts on “String interning, pointers and a dangerous side-effect

  1. Hai,
    I couldn’t understand it properly. What is the concept of
    interior or pinning pointer? Pls give some idea about this. It will be highly useful for me as I am highly manipulating string and string related methods in my project. Waiting for ur kind reply.

  2. Nish, I want one more help, but not regarding to this pointers. Is there any method to set/reset the access permission of a particular file or registry key programatically. Pls give me a reasonable solution.

  3. Hi nish,
    While using ‘SetFileSecurity’ and ‘RegSetKeySecurity’ , I met one problem. Both the functions set access permissions to the specified directory or Key. But the permission is not applied to the subfolders and files of the directory or the subkeys of the Key. How can I resolve this problem. Pls help me.

  4. Hi nish,
    Thank you very much. One more help , How the map name of a drive in registry is assigned? Is it random or fixed?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s