Skip to content

Divide by Zero in PerpendicDistSqrd (Delphi) #1061

@olivergrahl

Description

@olivergrahl

Glad I found this great library, thanks for providing it!

Here's a problem in the Delphi code (Clipper v2.0.1):

In

function PerpendicDistSqrd(const pt, line1, line2: TPoint64): double;
{$IFDEF INLINE} inline; {$ENDIF}
var
a,b,c,d: double;
begin
a := pt.X - line1.X;
b := pt.Y - line1.Y;
c := line2.X - line1.X;
d := line2.Y - line1.Y;
result := Iif((c = 0) and (d = 0),
0, Sqr(a * d - c * b) / (c * c + d * d));
end;

  result := Iif((c = 0) and (d = 0),
    0, Sqr(a * d - c * b) / (c * c + d * d));

should be

  if (c = 0) and (d = 0) then
    result := 0
  else
    result := Sqr(a * d - c * b) / (c * c + d * d);

or

  if (c = 0) and (d = 0) then
    exit(0);

  result := Sqr(a * d - c * b) / (c * c + d * d);

Background: Iif is just a function, not a coalesce operator like eval ? true : false. Both expressions used as params to Iif get evaluated, so Iif cannot be used to avoid division by zero here.

There are other questionable uses of Iif in the code, where at least for performance reasons, Iif should better be replaced by real if .. then .. else constructs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions