www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 18284] New: Can call struct method through a null pointer

https://issues.dlang.org/show_bug.cgi?id=18284

          Issue ID: 18284
           Summary: Can call struct method through a null pointer
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: normal
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: slavo5150 yahoo.com

The following example causes a runtime error as expected

import std.stdio;

class A
{
    void print() { writeln("hello"); }
}

void main()
{
    A a;
    assert(a is null);
    a.print();  // Runtime error as expected
}


However, by making `A` a struct, and accessing it through a pointer, there is
no runtime error.


import std.stdio;

struct A
{
    void print() { writeln("hello"); }
}

void main()
{
    A* a;
    assert(a is null);
    a.print();  // No runtime error.  Weird!
}


Adding a field to the struct, and accessing that field in the method will cause
a runtime error, as expected.

import std.stdio;

struct A
{
    int i;
    void print() { writeln(i); }
}

void main()
{
    A* a;
    assert(a is null);
    a.print();  // Runtime error as expected
}

--
Jan 22