git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: [PATCH v2] do not depend on signed integer overflow

From
Erik Faye-Lund <kusmabite@gmail.com>
Date
Oct 4, 2010, 22:46 UTC
Message-ID
<AANLkTim-DRC6k7wg=orYzVS81JRD7D6_UOr+w1ti_Owr@mail.gmail.com>
In-Reply-To
<20101004223331.GB9994@burratino>
On Tue, Oct 5, 2010 at 12:33 AM, Jonathan Nieder <jrnieder@gmail.com> wrote:
Show 31 quoted lines
> Erik Faye-Lund wrote:
>
>> +++ b/git-compat-util.h
>> @@ -28,6 +28,15 @@
>>  #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
>>  #define bitsizeof(x)  (CHAR_BIT * sizeof(x))
>>
>> +/*
>> + * Signed integer overflow is undefined in C, so here's a helper macro
>> + * to detect if the sum of two integers will overflow. The bitsize to
>> + * overflow at is taken from the first parameter, which must be zero
>> + * or positive.
>> + */
>> +#define signed_add_overflows(a, b) \
>> +    ((b) > ((INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a))) - (a)))
>
> Yes, I still like it.  This could be made closer to self-documenting
> like so:
>
> #define maximum_signed_value_of_type(a) \
>        (INTMAX_MAX >> (bitsizeof(intmax_t) - bitsizeof(a)))
>
> /*
>  * Signed overflow is undefined in C, so here's a helper macro
>  * to detect if the sum of two signed integers will overflow.
>  *
>  * Requires: a >= 0, typeof(a) equals typeof(b)
>  */
> #define signed_add_overflows(a, b) \
>        ((b) > maximum_signed_value_of_type(a) - (a))
>
I like that. Thanks for the suggestion, I'll roll a new version.
Previous: Jonathan Nieder
Message 3 of 3 in “do not depend on signed integer overflow”
  1. do not depend on signed integer overflowErik Faye-Lund, Oct 4, 2010
  2. Jonathan NiederOct 4, 2010
  3. Erik Faye-LundOct 4, 2010

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.