microsoft / dotnet

This repo is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.
https://devblogs.microsoft.com/dotnet/
MIT License
14.31k stars 2.21k forks source link

Null Checks in NativeAOT? #1377

Closed ChrisKoebke closed 1 year ago

ChrisKoebke commented 1 year ago

When I'm compiling the following code with .net-7.0 NativeAOT (win-x64), I get this accompanying exception:

Code (Program.cs):

unsafe {
    Test* t = null;

    Console.WriteLine("Before dereference");

    Console.WriteLine($"A = {t->A}");

    Console.WriteLine("After dereference");
}

struct Test {
    public int A;
}

Exception:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at Program.<Main>$(String[]) + 0x9a
   at ConsoleApp2!<BaseAddress>+0x16aa6b

I would have expected this behavior for managed objects, but pointers are considered unsafe and shouldn't check for null, therefore not throw a NullReferenceException?

Is this a bug, or, if not, is there a way to deactivate all null checks for unmanaged pointers? I am specifically looking for maximum speed and am using unmanaged code to achieve that here, but having null checks for all pointer dereferences kind of defeats the purpose here for me. I deliberately want my app to crash whenever I'm dereferencing a null pointer.

Thanks in advance for the help!

danmoseley commented 1 year ago

@ChrisKoebke sorry we missed this. The right repo to ask is dotnet/runtime. Could you please ask again there? I cannot transfer as it's not microsoft/*.