Search code examples
delphidelphi-xe2sortcomparefunction

SortCompareFunction with always same result creates EAccessViolation


What is the exact reason for the SortCompareObjects function getting an EAccessViolation if it always returns the same result (as opposed to a changing result e.g. with CompareText)?

function SortCompareObjects(Item1, Item2: Pointer): Integer;
begin
  Result := 1; // EAccessViolation
  // Result := CompareText(...); // No EAccessViolation
end;

MyObjectList: System.Contnrs.TObjectList;

MyObjectList := System.Contnrs.TObjectList.Create;

for i := 0 to x do
  MyObjectList.Add(AObject);

MyObjectList.Sort(@SortCompareObjects); // EAccesViolation 

Solution

  • A comparison sort algorithm accesses elements in an array under the assumption that the sort function has certain properties. Specifically,

    • If f(x,y)<0 then f(y,x)>0
    • If f(x,y)=0 then f(y,x)=0
    • If f(x,y)<0 and f(y,z)<0 then f(x,z)<0
    • f(x,x)=0

    The sort algorithm guarantees that it will sort the array if your function obeys the rules. Otherwise, if you don't obey the rules, all bets are off. Anything could happen. Don't be surprised if you encounter runtime errors. The most commonly seen, in my experience, is stack overflow, but access violation is plausible too.