'How can I resolve an access violation in managed C# code with structs?
Problem: When I attempt to access a derived property of a C# struct
, it results in an access violation error and the application exits abruptly (with status 0xC0000005). Unlike this question, it happens deterministically on a single property.
The struct definition is in a different library however I control both the client application and the library where the struct is defined.
There is no unmanaged code that I've written for this project. I'm using .NET 5 in both the client application and the library.
Things I've Tried:
- Changing the output to x64 in the library didn't help (the application output is x64)
- Enabling native code debugging (no information was provided)
MCVE:
Definition
public struct Foo
{
public const Double BarDivisor = 100.0;
// ...other properties...
public Int64 BarWholePart { get; }
public Int64 BarFractionalPart { get; }
public Double Bar => Bar + (BarFractionalPart / BarDivisor);
public Foo(Int64 wholePart, Int64 fractionalPart, /* ... */)
{
// ...
BarWholePart = wholePart;
BarFractionalPart = fractionalPart;
}
public static Foo Parse(Int64 whole, Int64 fractional)
{
return new Foo(whole, fractional);
// ...
}
}
Example of calling code
public void Baz(Foo bar)
{
// ...
Double foobar = bar.Bar; // this line results in a crash of the application
// ...
}
Exception Messages:
Exception thrown at 0x00007FF8C85A21A0 (coreclr.dll) in [application name removed]: 0xC0000005: Access violation writing location 0x000000E70B180FF8.
The Common Language Runtime cannot stop at this exception. Common causes include: incorrect COM interop marshalling and memory corruption. To investigate further use native-only debugging.
Unhandled exception at 0x00007FF8C85A21A0 (coreclr.dll) in [application name removed]: 0xC0000005: Access violation writing location 0x000000E70B180FF8.
The Common Language Runtime cannot stop at this exception. Common causes include: incorrect COM interop marshalling and memory corruption. To investigate further use native-only debugging.
Solution 1:[1]
This is caused because of a typographical error here
public Double Bar => Bar + (BarFractionalPart / BarDivisor);
BarWholePart
should be used instead of Bar
. This causes a StackOverflowException, but can sometimes cause an AccessViolationException in the debugger.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Justine Krejcha |