October 30th, 2024

Tip of the day #2: A safer arena allocator

The article discusses a safer arena allocator in C, highlighting memory management benefits, guard pages for out-of-bounds detection, and variations to enhance security and memory safety in programming.

Read original articleLink Icon
Tip of the day #2: A safer arena allocator

The article discusses the implementation of a safer arena allocator in C programming, emphasizing the benefits of using arenas for memory management. An arena allows multiple allocations with the same lifetime to be grouped together, simplifying code and improving performance. However, the author encountered a bug where writing past the bounds of an allocated array did not trigger a crash, leading to subtle data corruption. This issue arose because the operating system often allocates memory pages contiguously, making it difficult to detect out-of-bounds errors. To address this, the author suggests implementing guard pages before and after the allocated memory, which are marked as non-readable and non-writable. This approach helps catch out-of-bounds accesses by causing a crash when such accesses occur, making debugging easier. The article also explores variations of the arena allocator, including a paranoid approach that allocates separate pages for each allocation and a bucket per type approach to mitigate type confusion vulnerabilities. The author concludes by mentioning additional strategies for enhancing memory safety, such as using canaries and periodic checks.

- Using arenas can simplify memory management and improve performance in C programming.

- Implementing guard pages can help catch out-of-bounds memory accesses, making debugging easier.

- Variations of arena allocators can enhance security, including separate pages for allocations and type-specific buckets.

- The article highlights the importance of memory safety in programming and offers practical solutions to common issues.

Link Icon 3 comments
By @GuB-42 - 5 months
It is wrong to just use malloc() to make the arena? This way, sanitizers will still help you a bit. It will not help with everything you do within the arena, but it may detect it if you access outside the arena, like the problem the author has.

Other than that, I think using guard pages is the technique libefence (electric fence) uses.

By @mananaysiempre - 6 months
If you want to go further, ASAN and Valgrind both have APIs for integrating custom allocators. So you basically do what ASAN does with malloc in the first place—allocate (a bit more) memory, poison it, then pad all user allocations on both ends and only unpoison the actually requested part.