In searching for a highly intermittent memory corruption in a Delphi XE program, I have found a class constructor which initializes a few fields in the class, and then calls inherited. I believe the initializations were added after the constructor was first written, and accidentally in the wrong place. I have now corrected it to call inherited first. The exceptions from the memory corruption almost always occur in a method of this class.
Question: is it possible that this mistake caused an intermittent memory corruption? In tracing the code, it seems not, but I would really like this fix to be what solves the intermittent issue. That it does not occur for a while after fixing the problem will not prove that it has gone away.
Some code:
Tmyclass = class
ctype : integer;
ts : tstringlist;
th : thandle;
public
Constructor Create;
Destructor Destroy; override;
...
end;
Constructor Tmyclass.Create;
begin
ctype := 3;
doinit;
inherited;
end;
Here are typical steps of an object creation:
inheritedcall every parent – that is why you shall writeinheritedin both constructors and destructors.So,
inheritedcalls the parent method – you can even specify a parent level, or call none if you are sure you can do that (but may break the SOLID principles).In fact, when a
constructoris called, there is an hidden parameter added to the method:Source: official Delphi documentation
So you can be sure that, wherever the
inheritedis called, it will be safely handled. For instance, initialization of fields (reset to 0) will be processed only once, before all constructors are called.The
TObject.Createdefault constructor (the one called in yourinheritedline) is just abegin endvoid block, which does nothing. It is not even necessary/mandatory to callinheritedhere, but it is a good habit, since if you change your object hierarchy, it may be needed afterall.Only issue may be if some fields are set inside this
inheritedmethod (ctype := 2e.g.), after having been set in the child – but this is not compiler’s fault, this is up to user code!