John K
John K

Reputation: 28869

Can string pooling be corrupted or confused by use of unsafe C# code?

If I manipulate a managed C# string in place (for example, reverse its characters) by using pointers in an unsafe code block or method, can that unsafe implementation confuse or corrupt the .NET string pooling mechanisms?

The proposed string being manipulated is created in managed code and passed to an unsafe method to be manipulated.

Example of this scenario:

static void Main(string[] args) {
    string s = "this is a test";
    UnsafeReverse(s);
    Console.WriteLine(s); // displays "tset a si siht"
    // assume more managed strings are created and used along with the affected s. 
}

static unsafe void UnsafeReverse(string str) {
    int len = str.Length;

    fixed (char* pStr = str) {
        char* p1 = pStr;
        char* p2 = pStr + len - 1;

        char tmp;
        while (p1 < p2) {
            tmp = *p1;
            *p1 = *p2;
            *p2 = tmp;
            ++p1; --p2;
        }
    }
}

Upvotes: 4

Views: 148

Answers (1)

Hans Passant
Hans Passant

Reputation: 941665

Sure. Just write it like this to see the damage:

    static readonly string DontMessWithStrings = "this is a test";

    static void Main(string[] args) {
        string s = "this is a test";
        UnsafeReverse(s);
        Console.WriteLine(DontMessWithStrings);
    }

[Edit by OP] The result of displaying DontMessWithStrings is "tset a si siht" even though that variable is never directly touched by the string manipulation code!

Upvotes: 6

Related Questions