Bug 15994 – Trivial code compiled with dmd ends with code 11 !?

Status
RESOLVED
Resolution
INVALID
Severity
major
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2016-05-05T14:11:00Z
Last change time
2016-05-05T14:44:19Z
Assigned to
nobody
Creator
christophe

Comments

Comment #0 by christophe — 2016-05-05T14:11:45Z
Using DMD64 D Compiler v2.071.0 Trivial code is as follow ---- import std.stdio; class B { int n = 0; void foo() { n++; } } B b; void f() { b.foo(); } void main() { f(); } ---- Output is : Program exited with code -11 The code is compiled with default parameters of a freshly created dub project and executed with dub run. I implemented this useless code because I wanted to benchmark f(). The outcome was unexpected.
Comment #1 by public — 2016-05-05T14:15:20Z
Classes in D are reference types. By `B b` you define a null reference of B class and trying to call a method of it crashes program. You need to do `b = new B` somewhere.
Comment #2 by destructionator — 2016-05-05T14:44:19Z
Not a bug in D, simple programmer error. Pointers and references (not that all class objects are implicitly references, like Java or C#, but unlike C++) are automatically initialized to null exactly so it segfaults consistently to tell you that you made a mistake. To fix it, you need to initialize the object before use. For your case, you might just make B a struct instead of class. Classes' strength is found in interfaces and inheritance and you don't need that here, so struct is probably more appropriate. Structs are not references, so they will never be null.