Search code examples
formsdelphiaccess-violationdelphi-xe8

Assigning to RadioGroup Tag from Form Tag in XE8 causes access violation


I have recently upgraded from XE4 to XE8 and have come across a access violation when assigning a itemindex to a radio group. I was curious why in XE4 this works and XE8 it doesn't. All of the forms have been created when the main program starts up. This code works fine when debugging but when running as a standalone it throws the exception.

with TravelBookingForm do begin
   try
      rg1.itemindex:=tag-1;//not sure which causes the access violation
   except
      on E : Exception do
      begin
         showMessage(E.Message); //access violation message is shown
      end;
      rg1.tag := 0;
   end;
end;

NB: I have omitted code that isn't relevent


Solution

  • So after more testing I can confirm that rg1 is not nil and that it is the item causing the access violation.

    If rg1 is not nil and yet leads to an access violation then the most plausible explanation is that rg1 points to memory that has been freed. This matches the observation that the error occurs sometimes (outside debugger) and not others (under debugger).

    So, your program is destroying the form at some point, and then later referring to the form.

    Clearly that is an error in your program and you will need to make sure that you never refer to forms after they have been destroyed. Unfortunately the IDE encourages you to create all your forms once at startup, and hold references in global variables. This makes it all too easy to have stale references.

    If you used the full debug version of FastMM then that tool would be able to warn you when you attempt to access memory that has been freed.