How to be more careful about null pointers?
Marco Leise via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 29 14:16:17 PDT 2016
Am Tue, 29 Mar 2016 06:00:32 +0000
schrieb cy <dlang at verge.info.tm>:
> struct Database {
> string derp;
> Statement prepare(string s) {
> return Statement(1234);
> }
> }
>
> struct Statement {
> int member;
> void bind(int column, int value) {
> import std.stdio;
> writeln("derp",member);
> }
>
> }
>
>
> class Wrapper {
> Database something;
> Statement prep;
> this() {
> something = Database("...");
> prep = something.prepare("...");
> }
> }
>
> Wrapper oops;
> void initialize() {
> oops = new Wrapper();
> }
>
> class Entry {
> Wrapper parent;
> this(Wrapper parent) {
> //this.parent = parent;
> //oops
> parent = parent;
> }
> void usefulmethod() {
> parent.prep.bind(1,42);
> //parent.prep.execute();
> //parent.prep.reset();
> }
> }
>
> void main() {
> initialize();
> auto entry = new Entry(oops);
> entry.usefulmethod();
> }
>
> That program causes a segmentation fault on my machine. Somehow
> despite never initializing Entry.parent, a class object (whose
> default init is a null pointer), I can still call methods on it,
> access members on it, and call methods on those members. No
> warnings or errors. The segfault doesn't happen until the bind()
> method.
Dlang aborts programs that run into invalid states. Common
invalid states are failing contract assertions, out of memory
conditions or in this case a null-pointer dereference.
When designing Dlang, Walter decided that null pointers don't
require checks as the operating system will eventually abort
the program and debuggers are designed to assist you in this
situation.
Some people with a different programming background feel that
a modern language should wrap every pointer access in a check
and possibly throw a recoverable Exception here or make
null-pointer opt-in to begin with. The topic is still open for
discussion:
http://wiki.dlang.org/Language_issues#Null_References
--
Marco
More information about the Digitalmars-d-learn
mailing list