Though answers from links are not welcome, I found good material (including the code for checking whether overflow will (more generally, safely) add, subtract, multiply and divide integers):
https://www.securecoding.cert.org/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow
with discussions, etc.
Update
Since, when searching for an answer, you always want to immediately see a specific code that helps in solving a problem (rather than guessing, for example, how to write the verification condition for subtraction correctly, already knowing the correct answer for addition), here are some of the materials on this link that can be used as samples for their programs.
Check before adding:
#include <limits.h> void f(signed int si_a, signed int si_b) { signed int sum; if (((si_b > 0) && (si_a > (INT_MAX - si_b))) || ((si_b < 0) && (si_a < (INT_MIN - si_b)))) { /* Handle error */ } else { sum = si_a + si_b; } /* ... */ }
Check before subtraction:
#include <limits.h> void func(signed int si_a, signed int si_b) { signed int diff; if ((si_b > 0 && si_a < INT_MIN + si_b) || (si_b < 0 && si_a > INT_MAX + si_b)) { /* Handle error */ } else { diff = si_a - si_b; } /* ... */ }
Check before multiplication:
#include <limits.h> void func(signed int si_a, signed int si_b) { signed int result; if (si_a > 0) { /* si_a is positive */ if (si_b > 0) { /* si_a and si_b are positive */ if (si_a > (INT_MAX / si_b)) { /* Handle error */ } } else { /* si_a positive, si_b nonpositive */ if (si_b < (INT_MIN / si_a)) { /* Handle error */ } } /* si_a positive, si_b nonpositive */ } else { /* si_a is nonpositive */ if (si_b > 0) { /* si_a is nonpositive, si_b is positive */ if (si_a < (INT_MIN / si_b)) { /* Handle error */ } } else { /* si_a and si_b are nonpositive */ if ( (si_a != 0) && (si_b < (INT_MAX / si_a))) { /* Handle error */ } } /* End if si_a and si_b are nonpositive */ } /* End if si_a is nonpositive */ result = si_a * si_b; }
Check before dividing:
(or calculating the remainder)
#include <limits.h> void func(signed long s_a, signed long s_b) { signed long result; if ((s_b == 0) || ((s_a == LONG_MIN) && (s_b == -1))) { /* Handle error */ } else { result = s_a / s_b; } /* ... */ }
Well, if anyone is not too lazy to pull out the rest (related to the issue of the TS) code (as well as a description of all the essential points) here and arrange it carefully, you are welcome.