5 ms·
> Never dereference null pointers Something's wrong with us if this has to be mentioned in a list like this.
by amq 10y ago
> Never dereference null pointers
Something's wrong with us if this has to be mentioned in a list like this.
- Berobero 10y agoThe phasing was chosen to be provocative and attention grabbing (because, yeah, duh). The content of the point, however, is about avoiding undefined behavior, period, and not just lazily assuming "it works" means "it will always work".
- catnaroek 10y agoIf a programmer needs to reminded of this, they have no business programming.
- msbarnett 10y agoYou'd think. But there was a long argument here[1] not even a week ago with multiple people passionately asserting that they were entitled to be able to rely on completely predictable and non-fatal semantics when derefrencing a null pointer. [1]: https://news.ycombinator.com/item?id=13640505 https://news.ycombinator.com/item?id=13640505
- catnaroek 10y agoThe problem with C and C++ isn't so much that undefined behavior exists, but the fact that the rules that determine when a program has defined behavior aren't formalized rigorously enough. The C and C++ specifications are written in natural language, which always leaves room for ambiguity, no matter how pedantically one tries to write. If you want to convince a single other person that a C program you have written has no undefined behavior, then you and that person have to hopefully interpret English the same way. It would be completely hopeless to try to convince a hundred people that a nontrivial C program has no undefined behavior. And successful programs typically have way more than a hundred users.
- nwatson 10y agoThis used to compile and work just fine years ago (perhaps relying on undefined behavior): static void takes_null_reference_by_default(int& p = *((int*) nullptr)) { if (&p) ++p; } int main(int argc, char* argv[]) { int v1 = 15; int v2 = 25; takes_null_reference_by_default(v1); takes_null_reference_by_default(); takes_null_reference_by_default(*((int*) nullptr)); takes_null_reference_by_default(v2); std::cout << v1 << " " << v2 << std::endl; } Now g++ complains with: junk.cpp:5:10: warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; pointer may be assumed to always convert to true [-Wundefined-bool-conversion] ./a.out still runs though. And the de-references are just pseudo-de-references, it never "really" happens. EDIT: also mentioning the fits "delete this;" gave some people, but worked very well in the ACE Networking Library and various other places.