GitHub - Vanderhell/safemath: Safe allocation math for C — overflow-checked add, mul, align and buffer sizing. Single header, C99, no dependencies. · GitHub
Skip to content

Vanderhell/safemath

Repository files navigation

safemath

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.

Contract

  • Public API is bool-returning.
  • out == NULL returns false for every result-writing API.
  • On failure, *out is unchanged when out != NULL.
  • Zero-sized element calculations are mathematically valid.
  • sm_offset_add() uses exclusive-end semantics.
  • result == limit is 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.

API

  • sm_add, sm_sub, sm_mul
  • sm_array_bytes, sm_alloc_bytes, sm_offset_add
  • sm_is_pow2, sm_align_up, sm_align_up_bytes

Version macros:

  • SAFEMATH_VERSION_MAJOR
  • SAFEMATH_VERSION_MINOR
  • SAFEMATH_VERSION_PATCH
  • SAFEMATH_VERSION_NUMBER
  • SAFEMATH_VERSION_STRING

Optional diagnostics:

  • SAFEMATH_NODISCARD
  • SAFEMATH_NO_NODISCARD

Builtin selection:

  • SAFEMATH_FORCE_PORTABLE
  • SAFEMATH_FORCE_BUILTINS

Defining both force macros is a compile-time error.

Use

#include "safemath.h"

size_t bytes;
if (!sm_array_bytes(&bytes, count, sizeof(struct record))) {
    return false;
}

CMake package

Install and consume the header through the exported interface target:

find_package(safemath CONFIG REQUIRED)
target_link_libraries(app PRIVATE safemath::safemath)

Verified locally

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, user-reported

Sources of truth

About

Safe allocation math for C — overflow-checked add, mul, align and buffer sizing. Single header, C99, no dependencies.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

Contributors