문제

Recently I read a book about c# and was quite confused with the statement that null reference exception is not the same as access violation in native code when the pointer is dereferenced. The meaning of this is quite unclear for me, couldn't you explain it, please?

도움이 되었습니까?

해결책

In native code you access memory locations directly using pointers. If the pointer is 32 bit you can access around 4 billion virtual memory locations (2^32). However, not all virtual memory locations are mapped to physical memory and some of the locations are only mapped as read-only (e.g. code). If the native code tries to access a virtual memory location that is inaccessible you get an access violation on the CPU.

So access violations happens when you use an invalid pointer (either reading or writing the location pointed to by the pointer). The protection of the hardware memory manager helps you discover these errors by trapping the invalid access on the CPU and raising some form of error condition or exception. However, you can also have invalid pointers that results in access to memory locations that are accessible. Even though the access is invalid it is not discovered by the CPU and this can lead to memory corruption and other hard to fix bugs.

A common error in native code is to forget to initialize a pointer before using it. Often the pointer will then point to address 0 (also known as the null pointer). A strategy for catching this kind of error is to make the first page in the virtual address space (starting at address 0) inaccessible. When the invalid pointer is dereferenced you get an access violation. So in native code a null pointer error is reported as an access violation because address 0 is made inaccessible.

.NET executes on a virtual machine and does not provide pointers (unless you write unsafe code). The concept of access violation does not apply to .NET code. However, a .NET reference can be uninitialized (e.g. null). The virtual machine will throw a NullReferenceException when a null reference is dereferenced. Conceptually, this is somewhat similar to how native code null pointer errors are reported as access violations as described above but the concepts and mechanisms are different.

다른 팁

A NullReferenceException happens when you dereference an object reference that is null. null is a special value on the CLR which means "no object". It does not mean null pointer. In practice it is a null pointer but that is an implementation detail.

For managed code, an AccessViolationException makes no sense because there are no pointers in managed code. Don't confuse the conceptual level with the current implementation.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top