Header-only overflow-safe size math for C and C++.
safemath.h provides checked helpers for addition, subtraction, multiplication, allocation sizing, offset bounds, and power-of-two alignment.
- Public API is
bool-returning. out == NULLreturnsfalsefor every result-writing API.- On failure,
*outis unchanged whenout != NULL. - Zero-sized element calculations are mathematically valid.
sm_offset_add()uses exclusive-end semantics.result == limitis valid and represents one-past-end.- The return value does not identify the exact failure cause.
- Return values must be checked.
- The library has no third-party runtime dependencies. Standard headers are still required.
sm_add,sm_sub,sm_mulsm_array_bytes,sm_alloc_bytes,sm_offset_addsm_is_pow2,sm_align_up,sm_align_up_bytes
Version macros:
SAFEMATH_VERSION_MAJORSAFEMATH_VERSION_MINORSAFEMATH_VERSION_PATCHSAFEMATH_VERSION_NUMBERSAFEMATH_VERSION_STRING
Optional diagnostics:
SAFEMATH_NODISCARDSAFEMATH_NO_NODISCARD
Builtin selection:
SAFEMATH_FORCE_PORTABLESAFEMATH_FORCE_BUILTINS
Defining both force macros is a compile-time error.
#include "safemath.h"
size_t bytes;
if (!sm_array_bytes(&bytes, count, sizeof(struct record))) {
return false;
}Install and consume the header through the exported interface target:
find_package(safemath CONFIG REQUIRED)
target_link_libraries(app PRIVATE safemath::safemath)