Issue 15994 - Trivial code compiled with dmd ends with code 11 !?
Summary: Trivial code compiled with dmd ends with code 11 !?
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86_64 Linux
: P1 major
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2016-05-05 14:11 UTC by Christophe Meessen
Modified: 2016-05-05 14:44 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Christophe Meessen 2016-05-05 14:11:45 UTC
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 Dicebot 2016-05-05 14:15:20 UTC
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 Adam D. Ruppe 2016-05-05 14:44:19 UTC
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.