TList<T>.BinarySearch Access Violation if the list is empty
Summary
When a TList is empty and you try a binary search, it crashes. It also happens if you call TArrayHelper.BinarySearch directly.
System Information
- Operating system: Tested in Windows, should happen anywhere.
- Processor architecture: x86-64
- Compiler version: trunk 009816cb
- Device: Computer
Steps to reproduce
Create a new TList, then try a binary search without adding any items.
Example Project
{$mode delphi}
procedure TForm1.ButtonClick(Sender: TObject);
var
List: TList<integer>;
res: int64;
begin
List := TList<integer>.Create;
List.BinarySearch(2, res);
ShowMessage(inttostr(res));
end;
What is the current bug behavior?
Access violation
What is the expected (correct) behavior?
It should return item not found. Many algoritms start with an empty list and add values if the values are not already on the list. Those will fail when starting with an empty list.
Possible fixes
Add a check for empty arrays at the start of binarysearch. Suggested patch: 0001-fixes-Access-Violation-in-BinarySearch-if-empty.patch