4 ms·
Wait, can you even run into a null pointer reference error in Go?
by chx 2y ago
Wait, can you even run into a null pointer reference error in Go?
- topspin 2y agoYou can do this much: func main() { var p *int *p = 1 } panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x466462] That's memory safe. It's also common and terrible. As is Java's NullPointerException, C#'s NullReferenceException, Javascript's "is not a non-null object" and all the other, unnecessary and awful, yet memory safe manifestations of the same design mistake plaguing contemporary software. Understand that when Hoare coined the phrase "billion-dollar mistake," he was referring to his addition of null references to ALGOL W. ALGOL W references are not C pointers that allow willy-nilly pointer arithmetic and all the UB that come's with that. An explicit design goal of ALGOL W was to prevent unsafe dereferences. A dereference of a null reference in ALGOL W is defined behavior and yields a runtime error. NULL OR UNDEFINED REFERENCE An attempt has been made to access a record field using a null or never initialized reference. That said, ALGOL W isn't memory safe either: it attempts to mitigate memory violations, but this is not comprehensive.
- neonsunset 2y agoIf you add <WarningsAsErrors>nullable</WarningsAsErrors>, the below will not compile: var bytes = (byte[]?)null; Console.WriteLine(bytes.Length); That and, well, all variables must be assigned before use. You'd be right to point out it's a band-aid, a convenient one but still.
- topspin 2y agoAs you know, that has no benefit for any dependencies you have in play.
- neonsunset 2y agoWhat do you mean?
- topspin 2y agoMaking these warning into errors applies to the code you're writing. That's great: you're code won't dereference nulls for the most part. However, your code nearly always relies on dependencies. Those dependencies can still dereference nulls, and you can still encounter exceptions.
- neonsunset 2y agoThis is true. This is also rare in modern code, and impossible with standard library. Other libraries too are expected to adhere to nullability, which is a default whenever you create a new project, and many use the same WarningsAsErrors: nullable option on top of Nullable: enable set everywhere. At the end of the day, scenarios like a library spawning a Goroutine which tries to dereference a null where it doesn't expect and experiencing an unhandled panic, crashing the application, are practically impossible in .NET. It is not necessarily watertight, especially around JSON serialization, but it certainly evokes a "can't believe you guys still struggle with nulls/nils" kind of reaction.