Dynamic Object Creation
It’s been days since I’m working on a bug which always generates Access Violation errors.
By slicing and analyzing the pattern, this error always occurs when I’m trying to Free and NIL an object. I’m pretty much confident for the array index, so it should not be the reason for this error.
procedure FreeButtons(Buttons: TButtons); var Cnt : integer; begin for Cnt := Low(Buttons) to High(Buttons) do begin FreeAndNil(Buttons[Cnt]); end; SetLength(Buttons, 0); end;
This error appears after I ported my old SDI framework into an MDI one. It works perfectly fine earlier, but now definitely gives me some headache. I vaguely presume the reason behind this is the component ownership, but I still hasn’t convinced yet.
Then I stumbled on an article at http://delphi.about.com/od/kbcurt/a/dynamiccreation.htm about dynamic object creation. This article point out that if we’re going to free an object later, we should assign NIL as its parent.
Conclusion
So I finally came down to a conclusion and know exactly why the application always point to a non-readable address. It’s simply because when I’m destroying a form, the dynamically created components were also destroyed as well! This feature should not be a problem on its own, but when adding up the array index (which obviously not getting reset when the form destroyed) into account, problem occurs.
The workaround for this solution is to destroy the component myself, and set the value to nil.
FreeButtons(SES_Buttons_Category); FreeButtons(SES_Buttons_Subcategory); for I := 1 to MAX_ORDER do begin for J := 0 to MAX_OPTION do begin FreeSpeedButtons(SES_OR.Data[I].Options[J].Buttons); end; end;
Case Closed.
