Examples of intentional overflow in C

I know that signed overflows in C are undefined behavior according to the standard, but since in practice 2 additions for signed integers are quite often used (and even allowed, for example, using the -fwrapv option in gcc), I would like find a list of examples of programs that make good use of this fact.

Programs such as "incrementing counters that sometimes overflow" seem more suitable for unsigned integers, so I don't think they count.

Also, I do not consider compiler optimizations that might be included in this case, but useful programs that actually use signed overflows to compute something interesting.

+4
source share
2 answers

We used integer overflow to implement 64-bit arithmetic on 32-bit CPUs (in C and C ++, back in the 1980s). On top of my head, I think it was encoded something like this:

 // Add two-word integers void add64(unsigned a[2], unsigned b[2]) { unsigned t; // Add two-word integer b to a t = a[1]; a[1] += b[1]; // Lower word if (a[1] < t) // True if a[1]+b[1] overflows a[0]++; // Upper word } 

Now, if given, it is not used for overflow with an integer sign, but I think we really signed the integer forms of these routines, based on the same principle of overflow detection, to adjust the final result. (I just can't remember the details at the moment.) Most of the procedures were actually encoded as C preprocessor macros, as I recall.

+3
source

After discussing with a colleague at work (who does not have a StackOverflow account), he pointed me to this site:

http://www.gnu.org/software/autoconf/manual/autoconf-2.67/html_node/Signed-Overflow-Examples.html#Signed-Overflow-Examples

I accepted @David R Tribble's answer, as this is an example of a β€œreal world” of signed overflow, but I also leave the link here as a link.

+1
source

Source: https://habr.com/ru/post/1489502/


All Articles