Question

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 
Was it helpful?

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.

OTHER TIPS

Under the assumption that the sort algorithm is sequential ...

That's a very wrong assumption, one you don't need to make. First of all, unless you're on a trial version of Delphi, you can see the source code; It's QucikSort, not anything else. The second problem is, what's a "sequential" sort algorithm? I've never heard of one!

To answer your question directly, here's a snip of code from the QuickSort algorithm used by Delphi. SCompare is the function you supplied, the one that always reutrns 1

  while SCompare(SortList^[J], P) > 0 do
    Dec(J);

Since 1 is always grater then zero, that loop would never stop. It only stops when SortList^[j] generates an access violation, and that's bound to happen sooner or later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top