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?
int
in achar
array at the-1
index? (char
is 2 bytes,int
is 4 bytes) – Kieren Johnstone