27 #define SIZECALC_H
28
29 /*
30 * A machinery for safe calculation of sizes used when allocating memory.
31 *
32 * All size checks are performed against the SIZE_MAX (the maximum value for
33 * size_t). All numerical arguments as well as the result of calculation must
34 * be non-negative integers less than or equal to SIZE_MAX, otherwise the
35 * calculated size is considered unsafe.
36 *
37 * If the SIZECALC_ALLOC_THROWING_BAD_ALLOC macro is defined, then _ALLOC_
38 * helper macros throw the std::bad_alloc instead of returning NULL.
39 */
40
41 #include <stdint.h> /* SIZE_MAX for C99+ */
42 /* http://stackoverflow.com/questions/3472311/what-is-a-portable-method-to-find-the-maximum-value-of-size-t */
43 #ifndef SIZE_MAX
44 #define SIZE_MAX ((size_t)-1)
45 #endif
46
47 #define IS_SAFE_SIZE_T(x) ((x) >= 0 && (unsigned long long)(x) <= SIZE_MAX)
48
49 #define IS_SAFE_SIZE_MUL(m, n) \
50 (IS_SAFE_SIZE_T(m) && IS_SAFE_SIZE_T(n) && ((m) == 0 || (n) == 0 || (size_t)(n) <= (SIZE_MAX / (size_t)(m))))
51
52 #define IS_SAFE_SIZE_ADD(a, b) \
53 (IS_SAFE_SIZE_T(a) && IS_SAFE_SIZE_T(b) && (size_t)(b) <= (SIZE_MAX - (size_t)(a)))
54
55
56
57 /* Helper macros */
58
59 #ifdef SIZECALC_ALLOC_THROWING_BAD_ALLOC
60 #define FAILURE_RESULT throw std::bad_alloc()
61 #else
62 #define FAILURE_RESULT NULL
63 #endif
64
65 /*
66 * A helper macro to safely allocate an array of size m*n.
67 * Example usage:
|
27 #define SIZECALC_H
28
29 /*
30 * A machinery for safe calculation of sizes used when allocating memory.
31 *
32 * All size checks are performed against the SIZE_MAX (the maximum value for
33 * size_t). All numerical arguments as well as the result of calculation must
34 * be non-negative integers less than or equal to SIZE_MAX, otherwise the
35 * calculated size is considered unsafe.
36 *
37 * If the SIZECALC_ALLOC_THROWING_BAD_ALLOC macro is defined, then _ALLOC_
38 * helper macros throw the std::bad_alloc instead of returning NULL.
39 */
40
41 #include <stdint.h> /* SIZE_MAX for C99+ */
42 /* http://stackoverflow.com/questions/3472311/what-is-a-portable-method-to-find-the-maximum-value-of-size-t */
43 #ifndef SIZE_MAX
44 #define SIZE_MAX ((size_t)-1)
45 #endif
46
47 #define IS_SAFE_SIZE_T(x) (((x) + 1) > 0 && (unsigned long long)(x) - 1u < SIZE_MAX)
48
49 #define IS_SAFE_SIZE_MUL(m, n) \
50 (IS_SAFE_SIZE_T(m) && IS_SAFE_SIZE_T(n) && ((m) == 0 || (n) == 0 || (size_t)(n) <= (SIZE_MAX / (size_t)(m))))
51
52 #define IS_SAFE_SIZE_ADD(a, b) \
53 (IS_SAFE_SIZE_T(a) && IS_SAFE_SIZE_T(b) && (size_t)(b) <= (SIZE_MAX - (size_t)(a)))
54
55
56
57 /* Helper macros */
58
59 #ifdef SIZECALC_ALLOC_THROWING_BAD_ALLOC
60 #define FAILURE_RESULT throw std::bad_alloc()
61 #else
62 #define FAILURE_RESULT NULL
63 #endif
64
65 /*
66 * A helper macro to safely allocate an array of size m*n.
67 * Example usage:
|