Reputation: 22133
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:
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?
Upvotes: 11
Views: 4304
Reputation: 941665
You are missing the Big Bullet:
Which is very common, there's always lots of writable memory around in a .NET program. Including writing the element beyond the end of an array, it rarely bombs. Memory protection is granular at memory page boundaries, 4096 bytes on Windows. The .NET GC bumps that up considerably, the generational heap segments are nice big hunks of VM. Catching AVEs is very unwise.
Some code to play with:
class Program {
static unsafe void Main(string[] args) {
var arr = new byte[1];
for (int fill = 0; fill < 2 * 1024 - 64; ++fill) {
byte[] dummy = new byte[1024];
}
fixed (byte* p = &arr[0]) {
for (int ix = 1; ; ++ix)
p[ix] = 42;
}
}
}
Overshoots by about 1.5 megabytes.
Upvotes: 13
Reputation: 73482
Can unsafe code in C# cause memory corruption?
Answer is yes!, Consider the following example does that
int a = 10;
int* p = &a;
*(p+54)= 444;
CLR may or may not trap this.
Not all reads or writes through bad pointers lead to access violations, so an access violation usually indicates that several reads or writes have occurred through bad pointers, and that memory might be corrupted.
From Accessviolationexception Documentation
Upvotes: 7
Reputation: 28050
The memory write that caused the AccessViolationException did not happen, it does not do anything.
However: The fact that it tried to write to a wrong location is a very strong indicator that there might have been invalid write operations before (since your code is buggy), and those writes could have been pointing to locations that are writable but were not supposed to be changed.
Upvotes: 2
Reputation: 171208
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.
Upvotes: 10