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)| Item | Result |
|---|---|
| Windows x64, Visual Studio 2022 Community, MSVC 19.42.34444.0 | passed |
C99 build (clang -std=c99 under vcvars64) |
passed |
C++11 build (clang++ -std=c++11 under vcvars64) |
passed |
C test build (cl /std:c11) |
passed |
C++ wrapper build (cl /std:c++14) |
passed |
| CTest suite with auto and forced-portable paths | passed |
Package install and consumer smoke through find_package |
passed |
| Forced-builtin compile on this MSVC toolchain | failed as intended with a clear #error |
| WSL Ubuntu-24.04 verification | complete |