Bug 18284 – Can call struct method through a null pointer

Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2018-01-23T04:31:04Z
Last change time
2018-01-23T07:04:41Z
Assigned to
No Owner
Creator
Mike Franklin

Comments

Comment #0 by slavo5150 — 2018-01-23T04:31:04Z
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 }
Comment #1 by simen.kjaras — 2018-01-23T07:04:41Z
Try it again with print() being final on the class. The reason your code causes a runtime error with the class is the method is virtual, and so needs to be looked up in the vtable. No such lookup is necessary for the struct, and so no null-deref happens, and so no runtime error.