简体   繁体   中英

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 ?

Does arithmetic overflow overwrite data?

The behaviour of signed arithmetic overflow is undefined. It's neither guaranteed to overwrite data, nor guaranteed to not overwrite data.

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

Unsigned overflow is well defined. y will be 0, and there are no other side-effects.


Citation from the C++ standard (latest draft):

[basic.fundamental]

... The range of representable values for the unsigned type is 0 to 2 N −1 (inclusive); arithmetic for the unsigned type is performed modulo 2 N .

[Note 2: Unsigned arithmetic does not overflow. Overflow for signed arithmetic yields undefined behavior ([expr.pre]). — end note]


[expr.pre]

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

Since unsigned arithmetic is modular, the result can never be outside of representable values.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM