'Does arithmetic overflow overwrite data?

std::uint8_t x = 256; //Implicitly converts to 0

std::uint8_t y = 255;
y++;

For x, I assume everything is handled because 100000000 gets converted to 00000000 using some defined conversion from int to uint8_t. x's memory should be 0 00000000 not 1 00000000.

However with y I believe the overflow stays in memory. y is initially 11111111. After adding 1, it becomes 1 00000000. This wraps around back to 0 because y only looks at the 8 LSB.

Does the 1 after y++; stay in memory, or is it discarded when the addition is done? If it is there, could it corrupt data before y?



Solution 1:[1]

When using gcc with optimizations enabled, unless one uses the -fwrapv compiler option, integer overflow may arbitrarily disrupt program behavior, leading to memory corruption, even in cases where the result of the computation that overflowed would not be used. Reading through the published Rationale, it seems unlikely that the authors of the Standard would have expected a general-purpose compiler for a commonplace platform to behave in such fashion, but the Standard makes no attempt to anticipate and forbid all the gratuitously nonsensical ways implementations might process things.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 supercat