With list or arrays it's incredibly important when you want to delete things to go from the end of the array or list
downwards. If you go from start to finish in a for-loop you will die if more than one thing has to be deleted and further data moved. There's also a terminal condition where the item to be deleted is the last - trying to move data above that is fatal.
If you use Delphi or Free Pascal you don't have to bother with moving data - it's automatic - but you DO have to go downwards in a for-loop, otherwise you will be out of bounds even with one. This catches us all out from time to time. Code which looks fine may be dangerous.
Here's some pseudo-code to demonstrate why:
We have an array or list (a list is a dynamic array of pointers) of 5 elements, currently. We have a simple array of characters:
XXYXY
We want to delete the Ys.
WRONG:
for x := 0 to 4 do
begin
if ThisArray[x] = "Y" then
begin
ThisArray.delete[x]; // assuming you have such a command
// the length of the array is now 3 or 4, not 5
// but the loop counter will carry on, and BAM!
// After the first deletion (element 2) the array length is 4
// so no problem until x = 4, when it's out of bounds
end;
end;
If you do it downwards from (in this case) 5 to zero, nothing can go wrong because your x will always be within the bounds. This applies even to your own managed arrays - it's one of the many traps where perfectly legal source, which the compiler will no complain about, will kill you later!
-- Jim - When is there going to be a release?