Search code examples
delphistack-overflow

Stack overflow error delphi 7


I made application which has about 40 listboxes. I have infinite for loop that all the time ADD, DELETE or CHANGE items in these listboxes. after some time about 2 hours of ADDING, CHANGING and DELETING items i get "stack overflow" error message and application stops. I read on the internet it is something with memory. I have seen in the task manager that number of memory usage of my application is just growing and growing, but it never reduces. I think that my application never free the memory, so it is the problem. But i cant free listbox, because when i free listbox it dissapears. I didn't find any solution on the internet. Sorry for bad English, i think you can understand me. Thank you.

This example code is causing "Stack Overflow" error. Picture

procedure TForm1.BeginLoopClick(Sender: TObject); //begin the process
var
i,p:integer;
s:string;
begin
  listbox1.Clear;
  for i:= 1 to 10 do
  begin
  listbox1.Items.Add(IntToStr(i));

      if i= 7 then
      begin
      listbox1.Items[0]:='5';
      listbox1.Items.Delete(6);
      listbox1.Items.Delete(5);
      listbox1.Items.Delete(4);
      listbox1.Items.Delete(3);

      CallBeginLoopClick(sender);
      end;

  end;
end;

procedure TForm1.CallBeginLoopClick(Sender: TObject);
begin
      BeginLoopClick(sender);
end;

Solution

  • Let's run your code in pseudo steps:

    1. Clear content
    2. Add items 0 - 6, with data '1' - '7'
    3. Change item 0's data into '5'
    4. Delete item 3 - 6
    5. There are three items left: 0 - 2 with data '5', '2', '3'
    6. Goto step 1.
    

    The only conclusion you can make is that this code will run forever, because there is no escape:

    1. Clear content
    2. Add items 0 - 6, with data '1' - '7'
    3. Change item 0's data into '5'
    4. Delete item 3 - 6
    5. There are three items left: 0 - 2 with data '5', '2', '3'
    6. Clear content
    7. Add items 0 - 6, with data '1' - '7'
    8. Change item 0's data into '5'
    9. Delete item 3 - 6
    10. There are three items left: 0 - 2 with data '5', '2', '3'
    11. Clear content
    12. Add items 0 - 6, with data '1' - '7'
    13. Change item 0's data into '5'
    14. Delete item 3 - 6
    15. There are three items left: 0 - 2 with data '5', '2', '3'
    16. etc...
    

    The step that is missing from these steps is the call to BeginLoopClick. The routine calls itself (via another rutine) which is called recursion. All those calls are being remembered, because none will end. That is why your stack overflows (possibly among others like Windows Listbox internals).