coreutils
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: factor vs printf failure


From: Pádraig Brady
Subject: Re: factor vs printf failure
Date: Thu, 25 Jun 2015 16:31:27 +0100
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.6.0

On 25/06/15 15:38, Jim Meyering wrote:
> Hi Pádraig,
> 
> I noticed that a recent change accumulates the return value of printf
> into a variable of type size_t:
> 
> +static size_t n_out; /* How much data we've written to stdout.  */
> +
> ...
> -    printf ("%"PRIuMAX, t0);
> +    n_out += printf ("%"PRIuMAX, t0);
> 
> The problem is that when printf fails, it returns a negative int,
> which will be mapped to a very large size_t value in this case.
> When printf fails we don't really care about how buffering
> is done (that's the purpose of n_out), but it's worth at least
> a comment, if only to forestall reports from static analyzers.
> 
> Thanks for all of your work,

Yes I had discounted that as an issue, but you're right
that it's better to be explicit with the tricky issue
of integer conversion/overflow.  How about this comment,
and an explicit cast to placate any future warnings?

cheers,
Pádraig

diff --git a/src/factor.c b/src/factor.c
index 5b7ae22..902ada8 100644
--- a/src/factor.c
+++ b/src/factor.c
@@ -2331,7 +2331,10 @@ print_uintmaxes (uintmax_t t1, uintmax_t t0)
   uintmax_t q, r;

   if (t1 == 0)
-    n_out += printf ("%"PRIuMAX, t0);
+    {
+      /* n_out's value in inconsequential on error.  */
+      n_out += (size_t) printf ("%"PRIuMAX, t0);
+    }
   else
     {
       /* Use very plain code here since it seems hard to write fast code
@@ -2340,7 +2343,7 @@ print_uintmaxes (uintmax_t t1, uintmax_t t0)
       r = t1 % 1000000000;
       udiv_qrnnd (t0, r, r, t0, 1000000000);
       print_uintmaxes (q, t0);
-      n_out += printf ("%09u", (unsigned int) r);
+      n_out += (size_t) printf ("%09u", (unsigned int) r);
     }
 }




reply via email to

[Prev in Thread] Current Thread [Next in Thread]