Re: [PATCH] lib: gcd: prevent possible div by 0

From: Eric Dumazet
Date: Mon Sep 10 2012 - 05:12:26 EST


On Sun, 2012-09-09 at 17:03 +0200, Davidlohr Bueso wrote:
> Account for properties when a and/or b are 0:
> gcd(0, 0) = 0
> gcd(a, 0) = a
> gcd(0, b) = b
>
> Cc: stable@xxxxxxxxxxxxxxx
> Signed-off-by: Davidlohr Bueso <dave@xxxxxxx>
> ---
> lib/gcd.c | 3 +++
> 1 file changed, 3 insertions(+)
>
> diff --git a/lib/gcd.c b/lib/gcd.c
> index cce4f3c..7e163c6 100644
> --- a/lib/gcd.c
> +++ b/lib/gcd.c
> @@ -7,6 +7,9 @@ unsigned long gcd(unsigned long a, unsigned long b)
> {
> unsigned long r;
>
> + if (!a || !b)
> + return a | b;

This seems overkill

> +
> if (a < b)
> swap(a, b);

better here to :
if (!b)
return a;

> while ((r = a % b) != 0) {


--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/