malloc-guard is a C++ library designed for real-time applications where dynamic heap memory allocation is strictly forbidden. It uses dynamic GOT/PLT hooking to intercept standard memory allocator calls (malloc, free, realloc, calloc, etc.) and allows you to enforce configurable reactions (e.g. Abort, Log, Store Violations, or Custom Callbacks) when unexpected allocations occur in real-time threads.
You can include this library directly in your CMake project using FetchContent:
include(FetchContent)
FetchContent_Declare(
malloc_guard
GIT_REPOSITORY https://github.com/intrinsic-ai/malloc-guard.git
GIT_TAG main # Or a specific tag/commit hash
)
FetchContent_MakeAvailable(malloc_guard)
add_executable(my_application main.cc)
target_link_libraries(my_application PRIVATE malloc_guard::malloc_guard)
Alternatively, you can build and install the library system-wide or to a custom prefix:
mkdir build && cd build
cmake ..
make -j
# To install locally or system-wide
sudo make install
Once installed (either globally or locally via CMAKE_INSTALL_PREFIX), you can link against the library in your projects:
find_package(malloc_guard REQUIRED)
add_executable(my_application main.cc)
target_link_libraries(my_application PRIVATE malloc_guard::malloc_guard)
Add this repository to your Bazel workspace's MODULE.bazel:
bazel_dep(name = "malloc_guard")
# If using a local checkout:
local_path_override(
module_name = "malloc_guard",
path = "path/to/malloc-guard",
)
# Or, if pulling directly from git:
# git_override(
# module_name = "malloc_guard",
# remote = "https://github.com/intrinsic-ai/malloc-guard.git",
# commit = "<commit_hash>",
# )
Then depend on the target natively in your BUILD files:
cc_binary(
name = "my_application",
srcs = ["main.cc"],
deps = ["@malloc_guard//:malloc_guard"],
)
Include the main header in your C++ source files:
#include "intrinsic/malloc_guard.h"
You first need to enable the malloc hooks globally for the lifetime of your real-time threads. Then, use intrinsic::MallocGuard inside the real-time thread to intercept allocations:
// 1. Install the global hooks (do this outside your real-time section)
intrinsic::ScopedMallocGuardHook hook;
void MyRealtimeFunction() {
// 2. Set the reaction to abort for any allocations
intrinsic::SetThreadLocalMallocGuardReaction(intrinsic::MallocGuardReaction::kAbort);
// 3. Activate monitoring for this thread
intrinsic::MallocGuard guard;
while (true) {
// Critical real-time work
// Any call to malloc/new here will trigger the abort reaction.
}
}
Contributions are welcome! Please review:
This project is licensed under the Apache 2.0 License.
Disclaimer: This is not an officially supported Google product.
"Intrinsic" and "Intrinsic Core" are trademarks of Intrinsic Innovation LLC. See TRADEMARK.md for usage guidelines.
C++20 library for detecting and preventing dynamic heap allocations in real-time threads.
@intrinsic-ai/malloc-guard1.0.02026-09-24 |