1) As with any other operation in C, the application must ensure that:
- the type used for the calculation itself is large enough, and
- the type of variable in which the result is stored is large enough.
A way to ensure this is to set size limits for each operand before the operation. What suitable constraints depend on the algorithm and variable assignment.
2) If you use stdint.h of the C standard, you get guarantees of how large the variables are, portable. You should never use int when writing portable code.
As in the case of writing a safe division subroutine, 32-bit integers are required as parameters, then a calculation is performed on 64-bit integers and the result is returned as a 32-bit integer.
#include <stdint.h> #include <stdbool.h> /* Try to divide integer op1 by op2. Return true (success) or false (possibly overflow prevented). In case of success, write the quotient to res. In case of failure, res remains untouched. */ bool safe_int_div (int32_t* res, int32_t op1, int32_t op2) { if(op2 == 0) return false; int64_t res64 = (int64_t)op1 / (int64_t)op2; if(res64 > INT32_MAX || res64 < INT32_MIN) return false; *res = (int32_t)res64_t; return true; }
If you need more information about why the split failed, replace bool with an enumeration.
source share