[컴][프로그래밍] c/c++ 에서 overflow 검사 - 더하기

 

 

c/c++ 에서 add(+) 에 대해 overflows 검사하는 법

Precondition. Addition of unsigned integers can result in an integer overflow
if the sum of the left-hand side (LHS) and right-hand side (RHS) of an addition
operation is greater than UINT_MAX for addition of int type and ULLONG_MAX for
addition of unsigned long long type
Addition of signed integers is more complicated, as shown in Table 5–5.
As you test for these preconditions, make sure that the test itself does not
overflow. The tests in Table 5–5 are guaranteed not to overflow for appropriately signed values.

Postcondition. Another solution to detecting integer overflow is to perform
the addition and then evaluate the results of the operation. For example, to test
for overflow of signed integers, let sum = lhs + rhs. If lhs is non-negative and
sum < rhs, an overflow has occurred. Similarly, if lhs is negative and sum > rhs,
an overflow has occurred. In all other cases, the addition operation succeeds
without overflow. For unsigned integers, if the sum is smaller than either operand, an overflow has occurred.

 

Reference

  1. http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c
  2. http://ptgmedia.pearsoncmg.com/images/0321335724/samplechapter/seacord_ch05.pdf
  3. http://stackoverflow.com/questions/1815367/multiplication-of-large-numbers-how-to-catch-overflow

댓글 없음:

댓글 쓰기