|
memory_arena
|
Memory_Arenais a lightweight, high-performance memory allocator written in C, fully compatible with C++.
π View on GitHub π View full documentation
Memory_Arena is a lightweight, high-performance memory allocator written in C, fully compatible with C++. Designed around the arena allocation model, it organizes memory allocations into contiguous blocks for rapid allocation and bulk deallocation, significantly improving speed, memory efficiency, and reducing fragmentation. Library that is especially useful for systems programming, game engines, real-time applications, and scenarios where performance and memory efficiency are critical.
Instead of individually managing numerous memory operations (like malloc and free), it allows you to reset or reuse entire memory regions at once, perfect for scenarios involving temporary data, real-time rendering, or modular systems.
Memory_Arena is a lightweight, high-performance memory allocator written in C, fully compatible with C++. It leverages the arena allocation model to organize memory allocations into contiguous blocks, providing rapid allocation and bulk deallocationβideal for systems programming, game engines, real-time applications, and scenarios where performance and memory efficiency are critical.
I created this project after completing the C programming curriculum at Hive Helsinki (part of the 42 Network). My main goal was to deepen my understanding of low-level memory management, system programming and improve my skills by tackling practical challenges related to memory, performance, and library architecture.
Throughout the development of Memory_Arena, I've:
This project is part of my learning journey with C, demonstrating my ability to handle complex technical tasks, organize large-scale codebases effectively, and adhere to modern software development practices.
Ultimately, my goal is to deliver a library that is both educational for peers exploring systems programming, and genuinely useful as an efficient tool for developers tackling memory-intensive tasks.
Memory_Arena Features β‘ Fast Bump Allocation Allocations are performed linearly via pointer bumping, which offers near-zero overhead and avoids costly malloc bookkeeping. Ideal for temporary or scoped allocations.
π§ Flexible Allocation Allocate raw or zeroed memory, reallocate in place, or tag with debug labels. Supports alignment, hooks, stats, and thread safety. Designed for speed, clarity, and controlβwithout manual frees or fragmentation.
π Dynamic Growth & Shrinkage Arenas can automatically grow and optionally shrink when memory usage changes. This provides flexibility while maintaining predictable performance characteristics.
π Sub-Arenas & Markers Supports nested memory scopes via sub-arenas and arena_mark/arena_pop. Useful for implementing undo/rollback systems or scoped temporary memory.
π§΅ Thread-Safety (Opt-In) Enable safe multithreaded access to arena structures using ARENA_ENABLE_THREAD_SAFE. Internally guarded by recursive mutexes for safe reentry.
π Temporary Scratch Arenas Memory_Arena provides two systems for fast, reusable temporary memory: π’ Scratch Arena Pool (arena_scratch) Fast, reusable memory slots ideal for temporary workloads. Acquire/reset arenas on demand with thread-safe access, atomic tracking, and minimal overhead. Perfect for per-frame or per-task use. π§΅ Thread-Local Scratch Arenas (arena_tlscratch) Each thread gets its own fast, auto-resetting arena. Zero locks, zero setup after init, and perfect for throwaway allocations in tight loops or parallel workloads.
ποΈ Scoped Stack Frames Use arena_mark() and arena_pop() to create scoped memory lifetimes within an arena. Perfect for recursive algorithms, temporary parse buffers, or structured rollback. Fast, deterministic, and zero heap allocationsβstack frames live inside the arena itself.
πΎ Arena Snapshots Save and load arena memory to .bin files. Includes magic header/versioning, offset tracking, and buffer content. Great for debugging, state persistence, or fast startup by restoring memory from disk. Only works with arenas that own their buffer.
πΌοΈ Interactive Memory Visualizer A curses-based terminal visualizer is provided (using Notcurses) to observe arena activity live, allocations, resets, growth, and more. Helpful for profiling, education, or debugging.
π§© Allocation Labels & Hooks Attach labels to allocations for better diagnostics, or use custom hooks to monitor memory usage and capture metadata in real time.
π Debug Stats & Growth Tracking Internal statistics provide detailed insight into memory usage, peak allocations, growth events, and frame stack depth.
π οΈ Debug-Ready Built-in support for AddressSanitizer, ThreadSanitizer, and debug stats through CMake presets.
β£οΈ Memory Poisoning for Debugging Enable ARENA_POISON_MEMORY to fill freed memory with a poison pattern, helping you catch use-after-free bugs during development.
π§ͺ Fully Tested Includes over 30 unit and multithreaded tests. Supports ASAN, TSAN, and custom debug checks with arena_report_error() on critical paths.
πͺΆ Minimal Dependencies Written in pure C11 with no external dependencies outside optional visualizer.
π Well Documented Each function and internal module is documented using Doxygen with usage examples, groupings, and full cross-references. View full documentation
This project builds the memory arena as both:
Memory_Arena_static** β a static library (.a), linked directly into your program.Memory_Arena_shared** β a shared library (.so), loaded at runtime by the system (linked with pthread).Make sure the following tools are installed on your system:
--preset)visualizer)To help catch memory leaks, bugs, race conditions, deadlocks early, this project includes optional sanitizer support and debug features built into the CMake configuration.
You can enable the following features by setting CMake options (using presets or -D flags):
USE_ADDRESS_SANITIZER** β Detects memory errors like use-after-free, buffer overflows, etc.USE_THREAD_SANITIZER** β Detects data races in multi-threaded programs.ARENA_DEBUG_CHECKS** β Adds runtime checks to verify internal consistency.ARENA_POISON_MEMORY** β Overwrites memory with a known pattern when freed (e.g. 0xDEADBEEF) to detect use-after-free.ARENA_ENABLE_THREAD_SAFE** β Enables mutex locking inside the allocator for safe multi-threaded usage.β οΈ You cannot enable both ASAN and TSAN at the same time β the build will fail with a clear error if you try.
These options are defined in:
SanitizerConfig.cmake β applied conditionally based on flagsCMakeLists.txt β integrates them into the build and install processBy using these, you can easily switch between production-ready builds and debug-friendly builds to help test your project more safely.
The project uses CMake presets to manage different build configurations.
Use one of the following commands to configure a build:
Each preset enables or disables certain safety and debug features:
| Preset | Type | Thread-Safe | Poison Memory | Debug Checks | AddressSanitizer | ThreadSanitizer | Tests Enabled |
|---|---|---|---|---|---|---|---|
debug | Debug | β | β | β | β | β | β |
asan | Debug | β | β | β | β | β | β |
tsan | Debug | β | β | β | β | β | β |
release | Release | β | β | β | β | β | β |
πΉ Thread-Safe: Enables mutex locking internally.
πΉ Poison Memory: Fills freed memory with patterns (e.g.0xDEADBEEF) to catch bugs.
πΉ Debug Checks: Adds runtime checks for allocation errors, bounds, and double frees.
πΉ ASAN/TSAN: Compiler-level tools to detect bugs at runtime.
Once you've configured a preset (e.g. cmake –preset debug), you can build using these commands:
| Command | Description |
|---|---|
cmake --build --preset release | Build an optimized release version |
cmake --build --preset asan | Build with AddressSanitizer (memory error detection) |
cmake --build --preset tsan | Build with ThreadSanitizer (race condition checker) |
cmake --build --preset debug | Build to check debugs |
You can replace debug with asan, tsan, or release for different builds.
While these builds were originally designed to test the allocator itself, you can also use them while integrating the arena into your own program.
For example:
The static version (libMemory_Arena.a) is linked directly into your binary. It requires no special setup at runtime β ideal for portable or standalone builds.
This will include the memory arena directly into your binary, making it easy to distribute without worrying about runtime dependencies.
The shared version (libMemory_Arena.so) is loaded by the system at runtime. You must ensure the dynamic linker can locate it.
This installs the .so to /usr/local/lib, which is typically already searched by the system loader.
sudo, may conflict with system packages if multiple versions are installed.Use this if you want to test without global installation. The environment variable tells the loader where to find your .so.
.bashrc/.zshrc.π‘ Tip: You can also wrap it in a one-liner:
LD_LIBRARY_PATH=build/release ./my_app
This embeds a path inside your binary, instructing it to look for the shared library relative to its install location.
$ORIGIN refers to the location of the executable at runtime β useful when installing to a subfolder layout like:This project installs both CMake and pkg-config integration to simplify usage.
If you've installed the library globally (via sudo cmake --install), you can use find_package:
You get access to:
target_include_directoriesARENA_ENABLE_THREAD_SAFEπ‘ CMake will locate Memory_ArenaTargets.cmake and automatically configure everything.
If you're using a Makefile or a non-CMake build system:
Make sure PKG_CONFIG_PATH includes the install location (/usr/local/lib/pkgconfig).
This allows any build system to integrate with Memory_Arena using the standard pkg-config interface.
If you need to fully clean the Memory_Arena project β including all build files, installed artifacts, and pkg-config data β follow these steps:
If you used CMake presets (debug, release, etc.), simply delete the build folders:
If you've installed the library with:
You can manually remove the installed files:
Make sure to check /usr/local/lib, /usr/local/include, and /usr/local/lib/pkgconfig if you customized the install path.
If you had added this to your session:
It will reset on reboot, but you can manually unset it with:
You can also remove compile commands and CMake cache:
This project is licensed under the [MIT License](LICENSE).
You are free to use, modify, and distribute this code for academic, personal, or professional purposes. Attribution is appreciated but not required.
If you have any questions, suggestions, or feedback, feel free to reach out:
You're also welcome to open an issue or leave a comment on the repository.