Bug 14033 – runtime error about "auto ptr = cast(T*)buf" , T is class type

Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Windows
Creation time
2015-01-23T14:17:00Z
Last change time
2015-01-24T00:43:26Z
Assigned to
nobody
Creator
mzfhhhh

Comments

Comment #0 by mzfhhhh — 2015-01-23T14:17:16Z
struct stTest { int a; int b; } class clsTest { int a; int b; } void main() { int [100] buf ; auto stPtr = cast(stTest*)buf; stPtr.a = 123;//ok auto clsPtr = cast(clsTest*)buf; clsPtr.a = 123;//run time error }
Comment #1 by schveiguy — 2015-01-23T15:27:24Z
I think both should be a compile-time error.
Comment #2 by ag0aep6g — 2015-01-23T15:30:59Z
This is expected. `clsPtr.a` does two dereferences: 1) `clsPtr` is dereferenced and yields a `clsTest` object. Class objects are references (pointers) themselves. Since `buf` is all zeroes, you get a null Object. 2) To access the `a` field, that null reference is then dereferenced. Boom, segfault. In code: clsTest tmp = *clsPtr; /* tmp is null */ tmp.a = 123; /* dereferencing null */ Closing as invalid.
Comment #3 by mzfhhhh — 2015-01-24T00:43:26Z
i see,class and struct,their memory model is different,thanks. struct stTest { int a; int b; void foo(){} } class clsTest { int a; int b; void foo(){} } void main() { int [100] buf ; auto stPtr = cast(stTest*)buf; stPtr.a = 123;//ok stPtr.foo();//ok auto clsPtr = cast(clsTest)&buf; clsPtr.a = 123;//ok clsPtr.foo();//run time error,vfptr is not be assigned. }