Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Unsafe string manipulation

I use next unsafe code for string modifying:

public static unsafe void RemoveLastOne(ref string Str1)
    {
        if (Str1.Length < 1)
            return;

        int len = Str1.Length - 1;
        fixed (char* pCh1 = Str1)
        {
            int* pChi1 = (int*)pCh1;
            pCh1[len] = '\0';
            pChi1[-1] = len;
        }
    }

But some time later my C# programm crash with exception:

FatalExecutionEngineError: "The runtime has encountered a fatal error. The address of the error was at 0x6e9a80d9, on thread 0xcfc. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack."

If I change function "RemoveLastOne" to "Str1 = Str1.Remove(Str1.Length - 1);" program works fine.

Why exception happens? And how I can implement unsafe change string in C# correctly?

like image 441
Ilya Georgievsky Avatar asked Jul 11 '26 00:07

Ilya Georgievsky


1 Answers

String values in .Net are intended to be immutable. In this function you are taking an immutable value, mutating it in several visible ways (content and length) not to mention writing data before the original. I'm not surprised at all that this would result in a later CLR crash as it special cases String values in several places and writing before the pointer is simply dangerous.

I can't really see a reason why you'd want to do the unsafe manipulation here. The safe code is straight forward and won't cause these types of hard to track down bugs.

like image 106
JaredPar Avatar answered Jul 13 '26 14:07

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!