Bug 622 – There should be a warning for unininitalized class reference
Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2006-11-30T17:59:36Z
Last change time
2019-08-08T09:46:41Z
Assigned to
RazvanN
Creator
Andrei Khropov
Comments
Comment #0 by andkhropov — 2006-11-30T17:59:36Z
This error is very common for people with C++ background (I've already seen people asking questions about similar code several times):
----------------------------------------------
class Foo{
public int data;
}
void main()
{
Foo f; // obviously they try do this way as they got used to it in C++
// should be a warning here!
f.data = 1;// Access violation
}
----------------------------------------------
Comment #1 by wbaxter — 2006-11-30T18:16:29Z
Yes please! I make this mistake all the time, and every time it takes a few minutes tracking down why and where my program is crashing.
Comment #3 by bearophile_hugs — 2010-04-12T12:00:02Z
This bug is half-fixed: the compiler is now able to catch this bug at compile-time, but only if the code is compiled with -O.
I think the compiler has to catch this bug when not optimized mode is used too.
Comment #4 by razvan.nitu1305 — 2019-08-08T09:46:41Z
This issue would may be solved in 2 ways:
1. Issue a warning whenever you have an initialized class reference.
This is not a valid solution because you may want an initialized class reference that you will use later to point to another class instance.
2. Implement a dataflow analysis mechanism that will track all uses of f.
This is against dmd's principle of not doing complex dataflow analysis. Even it we were to implement this, there would still be situations were you cannot be sure whether you are dereferencing a null pointer:
class Foo
{
int a;
}
void fun(Foo a);
void main()
{
Foo f;
fun(f);
f.a; // => cannot know what fun did to a.
}
In addition, this sort of access violation is extremely easy to solve because you get a stack trace. Having a warning pointing it out is really redundant.
Closing as WONTFIX.