3 ms·
Dereferencing nil is not an unsafe memory access in Go, just like a null pointer exception in Java isn't unsafe. Both are well-defined operations (sure, they yi
by dbaupp 11y ago
Dereferencing nil is not an unsafe memory access in Go, just like a null pointer exception in Java isn't unsafe. Both are well-defined operations (sure, they yield errors, but they do so with 100% reliability and complete control), they're not undefined behaviour like in C or C++.
Unsafe memory accesses refers to things like accessing an array out-of-bounds, or reading from a pointer that has already been freed. (I suspect a data race could actually cause an array to be accessed out of bounds in Go, but I'm not sure.)
- brobinson 11y agoThanks for the clarification! What if instead of the sender goroutine setting the pointer to nil, the GC frees the object that the pointer was pointing to before the recipient goroutine reads it? Wouldn't that be considered "reading from a pointer that has already been freed"?
- ustolemyname 11y agoThat can't happen. The GC won't free the object until nothing references it, and in your proposed scenario either the channel or receiving goroutine will have a valid reference.