Bug 9904 – typeof(null) can be casted to aggregate type if .sizeof equals size of pointer
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-04-08T07:42:00Z
Last change time
2013-06-07T22:20:34Z
Keywords
accepts-invalid, pull
Assigned to
nobody
Creator
andrej.mitrovich
Comments
Comment #0 by andrej.mitrovich — 2013-04-08T07:42:22Z
struct S1
{
int x;
}
struct S2
{
int x;
byte b;
}
void main()
{
static assert(S1.sizeof == typeof(null).sizeof);
auto s1 = cast(S1)null; // compiles, should not
static assert(S2.sizeof != typeof(null).sizeof);
auto s2 = cast(S2)null; // NG, as it should
}
Comment #1 by andrej.mitrovich — 2013-04-08T07:47:34Z
(In reply to comment #0)
> struct S1
> {
> int x;
> }
>
> struct S2
> {
> int x;
> byte b;
> }
Those should really use size_t to reproduce on all systems:
> struct S1
> {
> size_t x;
> }
>
> struct S2
> {
> size_t x;
> byte b;
> }
Comment #2 by bearophile_hugs — 2013-04-08T10:01:36Z
(In reply to comment #1)
> Those should really use size_t to reproduce on all systems:
>
> > struct S1
> > {
> > size_t x;
> > }
> >
> > struct S2
> > {
> > size_t x;
> > byte b;
> > }
Why is that cast a problem/bug? Maybe there is no compiler bug here.
Comment #3 by andrej.mitrovich — 2013-04-08T10:31:56Z
(In reply to comment #2)
> (In reply to comment #1)
>
> > Those should really use size_t to reproduce on all systems:
> >
> > > struct S1
> > > {
> > > size_t x;
> > > }
> > >
> > > struct S2
> > > {
> > > size_t x;
> > > byte b;
> > > }
>
> Why is that cast a problem/bug? Maybe there is no compiler bug here.
It may not do what the user expects. For example they might think this is a good way to initialize the struct to its default value, but it's wrong:
import std.math;
struct S
{
float x;
}
void main()
{
auto s1 = S.init;
auto s2 = cast(S)null;
assert(isnan(s1.x));
assert(isnan(s2.x)); // fails
}
Comment #4 by github-bugzilla — 2013-06-07T22:19:54Z