SIGSEGV in TStringGrid.Free when focused lazarus / 31-LCL ---------------------------------------------------------------------- mmxngg · 2012-12-12 22:32 Seems a bug but...http://bugs.freepascal.org/view.php?id=23478 So there is no way to create or manage a grid at runtime ? Really ? ---------------------------------------------------------------------- JuhaManninen · 2012-12-12 23:08 Quote from: mmxngg on December 12, 2012, 11:32:03 pmSo there is no way to create or manage a grid at runtime ? Really ?  Yes there is but you freed a component that was added on a form at design time. It is a no no... Juha ---------------------------------------------------------------------- mmxngg · 2012-12-12 23:24 Ah ok...but i posted a simple example for reproduce the case  This is a portion of real code in my project : Code: [Select]  SGDomanda := TStringGrid.Create(SBQuestionario);   with (SGDomanda) do   begin     Left                     := $10;     Top                      := CPos;     Width                    := $28E;     Height                   := $30;     FixedCols                := $0;     RowCount                 := $2;     ScrollBars               := ssNone;     TitleStyle               := tsNative;     Options                  := [goEditing, goTabs];     Parent                   := SBQuestionario;     SGFixedCol               := Columns.Add;     SGFixedCol.Width         := $1F8;     SGFixedCol.Title.Caption := 'Domanda';     SGFixedCol               := Columns.Add;     SGFixedCol.Width         := $4C;     SGFixedCol.Title.Caption := 'Risposte (da)';     SGFixedCol               := Columns.Add;     SGFixedCol.Width         := $46;     SGFixedCol.Title.Caption := 'Risposte (a)';     Name                     := 'SGDM' + IdxLastD;     OnExit                   := @ResetGridPos;     OnKeyDown                := @ChangeGridFocus;     OnSelectCell             := @ScrollView;   end;   ....   SGDomanda.SetFocus;   ....   SGDomanda.Free; // SIGSEGV Of course without the focus all works fine. ---------------------------------------------------------------------- JuhaManninen · 2012-12-12 23:45 You still don't need to free it because the Owner is SBQuestionario (whatever it is). If you really want to free it explicitly, do this : Code: [Select]SGDomanda := TStringGrid.Create(Nil); Juha ---------------------------------------------------------------------- mmxngg · 2012-12-13 00:11 SBQuestionario is a ScrollBox added on a form at design time and can hold one or more grid created at runtime by the user. SGDomanda is a simply dummy variable for create a new grid but i have to manage all by component name because the user can add or remove one or more grid. I have the same management for all components generated at runtime and only the grid has this problem. ---------------------------------------------------------------------- taazz · 2012-12-13 00:43 as far as I can understand calling setfocus and then free creates some kind of conflict in the components message handling loop I assume that the setfocus use some kind of async method to handle the shift of focus state which is executed after the component's free is called and of course it raises the sigsegv error. try to avoid calling it there is no reason to call focus, I do not have all the code to see why you need it but since you are creating and freeing the component in the same routine I see no reason to change the focus state at all. by the way I really do not see a reason to use a stringgrid at all if it is created and released inside a single routine try to use a non visual class instead. ---------------------------------------------------------------------- mmxngg · 2012-12-13 01:19 The focus is set on the creation routine but of course the free is called elsewhere. This is a screenshot of the application with the ScrollBox that contains multiple grids that may be deleted, modified or added through the buttons on the right and bottom (also the buttons inside the ScrollBox are created at runtime). http://postimage.org/image/mk7wm1wfp/ I can not post 3512 lines of code to explain that there is an error in freeing a grid that has the focus. For me it is an obvious bug, beyond how they are created, managed or released. To work around this problem i will check the component type before releasing it and remove the focus if necessary... ---------------------------------------------------------------------- taazz · 2012-12-13 02:32 I'm sorry, but the test code you have provided was simplified to much, making it impossible to get the correct flow of the problem. Any way you are right this is a bug and needs to be addressed. ---------------------------------------------------------------------- mmxngg · 2012-12-13 11:25 A simple and complete example to understand the case. I used the SpeedButton that do not change the focus. Code: [Select]unit Unit1; {$mode objfpc}{$H+} interface uses   Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,   Grids, Buttons; type   { TForm1 }   TForm1 = class(TForm)     ComboBox1: TComboBox;     ScrollBox1: TScrollBox;     SpeedButton1: TSpeedButton;     SpeedButton2: TSpeedButton;     SpeedButton3: TSpeedButton;     procedure FormCreate(Sender: TObject);     procedure SpeedButton1Click(Sender: TObject);     procedure SpeedButton2Click(Sender: TObject);     procedure SpeedButton3Click(Sender: TObject);   private     { private declarations }     NGrid: Integer;   public     { public declarations }   end; var   Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin   Randomize;   NGrid := $0; end; procedure TForm1.SpeedButton1Click(Sender: TObject); var   Grid: TStringGrid; begin   Grid := TStringGrid.Create(ScrollBox1);   with (Grid) do   begin     Top       := Random(Form1.Height);     Left      := Random(Form1.Width);     Height    := 48;     Width     := 132;     FixedCols := 0;     FixedRows := 0;     RowCount  := 2;     ColCount  := 2;     Parent    := ScrollBox1;     Name      := 'Grid' + Format('%.4d', [NGrid]);     ComboBox1.Items.Add(Name);   end;   Inc(NGrid); end; procedure TForm1.SpeedButton2Click(Sender: TObject); begin   if not (ComboBox1.ItemIndex < 0) then   begin     ScrollBox1.FindComponent(ComboBox1.Caption).Free;     ComboBox1.Items.Delete(ComboBox1.ItemIndex);     ComboBox1.Refresh;   end; end; procedure TForm1.SpeedButton3Click(Sender: TObject); begin   if not (ComboBox1.ItemIndex < 0) then     TStringGrid(ScrollBox1.FindComponent(ComboBox1.Caption)).SetFocus; end; end. ---------------------------------------------------------------------- Blaazen · 2012-12-13 11:50 Problem is in use of method Free. Use FreeThenNil instead. It is in unit LCLProc. Code: [Select]procedure TForm1.SpeedButton2Click(Sender: TObject); var   Grid: TStringGrid;    begin   if not (ComboBox1.ItemIndex < 0) then   begin     Grid:=TStringGrid(ScrollBox1.FindComponent(ComboBox1.Items[ComboBo x1.ItemIndex]));     FreeThenNil(Grid);     ComboBox1.Items.Delete(ComboBox1.ItemIndex);     ComboBox1.Refresh;   end; end;      also, isn't it more handy to write Code: [Select]if ComboBox1.ItemIndex >= 0 then ...? ---------------------------------------------------------------------- mmxngg · 2012-12-13 12:46 I used PerformTab to move the focus to the next component (most useful in my case). Both methods work but it is a trick to bypass the problem... no ? Quote from: Blaazen on December 13, 2012, 12:50:31 pmalso, isn't it more handy to write Code: [Select]if ComboBox1.ItemIndex >= 0 then ...?  It 's the same...school of thought  (maybe the compiler changes the jump instruction but all have the same cycle) ---------------------------------------------------------------------- Blaazen · 2012-12-13 13:24 I am not sure but IMO it will be related to focus. You use TSpeedButton to delete selected Grid but TSpeedButton itself cannot have focus (it is derived from TGraphicControl). Therefore Lazarus tries to keep focus on selected component which deleted at the same time - > crash  . ---------------------------------------------------------------------- taazz · 2012-12-13 16:31 @Blaazen Actually inability to receive focus means that there is no focus shift by the mouse and no kind of effort to keep the focus on the already focused component. Have you actually looked at the call stack when the exception is raised? Expand it to show more that 10 previous results and you will see that the exception is raised when the setfocus is called to shift the focus to the form it self. I'm assuming that the problem is that the widgetset.Setfocus  is called twice once from the form and once from the component receiving the focus, that needs to be cleaned up I guess but I'm not well versed in the lcl to actually have an opinion at this point.. ---------------------------------------------------------------------- Blaazen · 2012-12-13 16:55 Here it shows: Code: [Select]#0 CLASSES$_$TLIST_$__$$_GET$LONGINT$$POINTER at :0 #1 ?? at :0 #2 COLROWTOOFFSET(0x7ffff7fabf30, true, true, 0, 1431655765, 1431655765) at grids.pas:5506 #3 CELLRECT(0x7ffff7fabf30, 0, 0) at grids.pas:3137 #4 INVALIDATECELL(0x7ffff7fabf30, 0, 0, false) at grids.pas:7251 #5 INVALIDATECELL(0x7ffff7fabf30, 0, 0) at grids.pas:7239 #6 INVALIDATEFOCUSED(0x7ffff7fabf30) at grids.pas:6802 #7 DOEXIT(0x7ffff7fabf30) at grids.pas:6480 #8 CMEXIT(0x7ffff7fabf30, {MSG = 45083, UNUSEDMSG = 1431655765, WPARAM = 0, LPARAM = 0, RESULT = 0}) at include/wincontrol.inc:8146 #9 SYSTEM$_$TOBJECT_$__$$_DISPATCH$formal at :0 #10 ?? at :0 #11 ?? at :0 #12 ?? at :0 #13 ?? at :0 #14 ?? at :0 #15 ?? at :0 #16 ?? at :0 #17 .Ld178 at :0 #18 ?? at :0 #19 ?? at :0 Probably it may differ on other platform (I have Qt4). ---------------------------------------------------------------------- eny · 2012-12-13 18:49 Quote from: mmxngg on December 13, 2012, 01:46:19 pmIt 's the same...school of thought  (maybe the compiler changes the jump instruction but all have the same cycle)It actually isn't. More obfuscated, less easy to understand. But of course if you're the only one maintaining it, no problem. ---------------------------------------------------------------------- JuhaManninen · 2012-12-13 20:31 I would like to repeat: You should never free a component that is owned by another component : Code: [Select]Grid := TStringGrid.Create(ScrollBox1); ... Grid.Free;  // <- Bad!  Owned by ScrollBox1. Maybe it did not cause the crash. Maybe the focus did it. Don't know. Anyway, freeing a focused control feels like begging for problems. Why would you do such thing? Maybe deleting the control first from its parent's collection first would do it cleanly. Often the GUIs are altered by changing the visibility of controls. mmxngg, your "bug" report was very different. There you freed a component added at design time. Juha ---------------------------------------------------------------------- taazz · 2012-12-14 01:13 Quote from: JuhaManninen on December 13, 2012, 09:31:29 pmI would like to repeat: You should never free a component that is owned by another component : Code: [Select]Grid := TStringGrid.Create(ScrollBox1); ... Grid.Free;  // <- Bad!  Owned by ScrollBox1. Although I agree that the owner is responsible to handle the clean up and life time of the objects it owns it is desirable to be able to free those components outside the owner mechanism and it works as expected.  Quote from: JuhaManninen on December 13, 2012, 09:31:29 pmMaybe it did not cause the crash. Maybe the focus did it. Don't know. Anyway, freeing a focused control feels like begging for problems. Why would you do such thing? Maybe deleting the control first from its parent's collection first would do it cleanly. Often the GUIs are altered by changing the visibility of controls. mmxngg, your "bug" report was very different. There you freed a component added at design time. Juha In my 20 min attempt to pin point the culprit I came to the conclusion that the focus is the problem. I do not know what or where exactly but as far as I can understand there is probably a variabe or a list somewhere that keeps a reference and does free it when it should. The search goes on this is a major problem in my book. ---------------------------------------------------------------------- mmxngg · 2012-12-14 11:21 I used 10 minutes to figure out where the problem was and : - FreeThenNil does not work - The owner is not the problem because the bug remain also with Create(nil) - Created at design or runtime...nothing changes...still does not work In the destructor, the code searches the next control of the parent for set the new focus and takes an handle that is already freed. Moving the TCustomGrid inherited destroy at the beginning of the procedure the problem disappears but i don't think that is the correct solution. ---------------------------------------------------------------------- User137 · 2012-12-14 12:39 Quote from: mmxngg on December 14, 2012, 12:21:21 pm- FreeThenNil does not workCode: [Select]FreeAndNil(yourObjectName); ---------------------------------------------------------------------- mmxngg · 2012-12-14 13:09 I have not tried but it's useless for release the grid within application. Maybe can works in the destructor of TCustomGrid for release all object. ---------------------------------------------------------------------- JuhaManninen · 2012-12-14 18:08 Quote from: mmxngg on December 14, 2012, 02:09:12 pmMaybe can works in the destructor of TCustomGrid for release all object. Hmmm... Do you mean the Grid somehow owns the objects? You should separate data/logic and GUI as much as possible. Copy the data to/from the GUI controls. The life-time of a control should not depend so much on the life-time of data. I recommend that you let the Owner of the Grid handle its life-time. You can show/hide it with Visible := True/False, and reuse them as needed. This is the best way resource-wise, too. Creating a GUI control takes longer that just showing an existing control. Juha ---------------------------------------------------------------------- mmxngg · 2012-12-14 19:20 Quote from: JuhaManninen on December 14, 2012, 07:08:55 pmHmmm... Do you mean the Grid somehow owns the objects? TCustomGrid allocates some resources for its internal management and releases them with FreeThenNil. From destructor TCustomGrid.Destroy in grids.pas Code: [Select]  FreeThenNil(FColumns);   FreeThenNil(FGCache.AccumWidth);   FreeThenNil(FGCache.AccumHeight);   FreeThenNil(FCols);   FreeThenNil(FRows); Moving this code after the inherited destroy or maybe use FreeAndNil "fix" the bug (yes, it's a bug...just try a debug session) Quote from: JuhaManninen on December 14, 2012, 07:08:55 pmYou should separate data/logic and GUI as much as possible. Copy the data to/from the GUI controls. The life-time of a control should not depend so much on the life-time of data. I recommend that you let the Owner of the Grid handle its life-time. You can show/hide it with Visible := True/False, and reuse them as needed. This is the best way resource-wise, too. Creating a GUI control takes longer that just showing an existing control. Yeah, create and release a resource requires more time, it is true, but hide / show it only when required is a contorted solution at least in my case (too much works for nothing). Anyway i fix the problem simply called PerformTab before the Free (a perfect solution for me) but anyone who tries to free a focused grid will take the same issue. ---------------------------------------------------------------------- JuhaManninen · 2012-12-15 00:22 Ok, it looks like a bug, especially as the other focused controls can be freed. I applied your code change in r39544 and updated the bug report accordingly. Thanks, and sorry I first doubted the bug report strongly. I personally still would not free a focused control but that is another issue. Juha [Edit:] Jesus Reyes already fixed it in a better way. Thanks. See the bug report for details. ---------------------------------------------------------------------- mmxngg · 2012-12-16 02:20 Oh perfect. Can you tell me what is the file patched ? I prefer don't install a new version Thank you [Edit1:] Jesus Reyes fix is pefect, well done. [Edit2:] Crash with a different issue, work in progress.