-
Notifications
You must be signed in to change notification settings - Fork 0
/
safe-math.c
44 lines (33 loc) · 822 Bytes
/
safe-math.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/** @file
Implements checked math functions which handle errors by terminating the
program with an error message.
*/
#include "safe-math.h"
#include <stdint.h>
#include "error-handling.h"
/** Adds two sizes and terminates the program on overflows.
@param a The first summand.
@param b The second summand.
@return The sum of a and b.
*/
size_t CR_SafeAdd(size_t a, size_t b)
{
if(a > SIZE_MAX - b)
{
CR_ExitFailure("overflow calculating object size");
}
return a + b;
}
/** Multiplies two sizes and terminates the program on overflows.
@param a The first factor.
@param b The second factor.
@return The product of a and b.
*/
size_t CR_SafeMultiply(size_t a, size_t b)
{
if(b != 0 && a > SIZE_MAX/b)
{
CR_ExitFailure("overflow calculating object size");
}
return a * b;
}