Can unsafe code in C# cause memory corruption?
.net, c#
Solution
Accessing a pointer to an invalid random memory location
If it is a read, it is safe. If it was a write it is unsafe if the memory location happened to be valid, but you did not own it. You'll be scribbling over random memory locations.
And as a corollary, is it safe to catch AccessViolationExceptions from unsafe code?
No, because that exception tells you a) that you have a bug and b) that memory might be corrupted which cannot be repaired. Catch it and tear down the process asap.
Problem
Basically, memory corruption is caused by overwriting memory you're not supposed to overwrite. I am wondering if this is possible with unsafe code in C# (i.e. not by calling into external unmanaged code). I see two possible cases: - Accessing a null pointer -> Trapped by the CLR, throws a NullReferenceException - Accessing a pointer to an invalid random memory location -> Trapped by the CLR, throws an AccessViolationException In both cases it seems the runtime detects and prevents the potential memory corruption from taking place. Therefore, is it possible to corrupt memory from C# using unsafe code? And as a corollary, is it safe to catch AccessViolationExceptions from unsafe code?