Compare commits

...

16 Commits

Author SHA1 Message Date
seajee
c5a38cc501 v1.1.3 - Align Arena_Region data flexible array member 2026-01-14 18:11:15 +01:00
seajee
1ffc6e1402 Include stdalign.h 2026-01-10 17:45:01 +01:00
seajee
2d465afc7f v1.1.2 Minor changes; check result of alloc in arena_copy() 2026-01-10 17:42:14 +01:00
seajee
1b7e73d3cb v1.1.1 Implement memory alignment; improve docs 2025-11-18 21:27:33 +01:00
seajee
1956855adf v1.1.0 - New helper functions: arena_copy(), arena_strdup() 2025-11-18 18:22:02 +01:00
seajee
bbf3371038 Update docs and assertions 2025-11-17 02:49:43 +01:00
seajee
38decaf81a 1.0.3 - Renamed parameter bytes to size in arena_alloc() 2025-09-10 21:49:09 +02:00
seajee
9657cfdb43 v1.0.2 release 2025-09-06 02:22:52 +02:00
seajee
4c069c0945 v1.0.1 - Prevent name mangling of functions; don't reset region_capacity in arena_free() 2025-08-02 15:13:38 +02:00
seajee
e583d87285 Remove new line 2025-07-24 21:04:21 +02:00
seajee
529e3918e1 v1.0.0 - Initial release 2025-07-24 19:57:43 +02:00
seajee
562191e10c Complete Arena struct typedef 2025-07-24 16:00:29 +02:00
seajee
2c636c524d Simplify arena_alloc implementation 2025-07-24 15:55:26 +02:00
seajee
ff948662e5 Update README.md 2025-07-24 15:46:08 +02:00
seajee
f9b6b1e7f0 Add .gitignore 2025-07-24 15:39:15 +02:00
seajee
26fd7f1118 Improve modularity, introduce arena_create() 2025-07-24 15:38:21 +02:00
4 changed files with 339 additions and 85 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
test

View File

@@ -1,7 +1,8 @@
# arena.h
A single header library that implements
[region-based memory management](https://en.wikipedia.org/wiki/Region-based_memory_management) in C.
[region-based memory management](https://en.wikipedia.org/wiki/Region-based_memory_management)
in C using a linked list approach.
## Example
@@ -11,12 +12,13 @@ A single header library that implements
int main(void)
{
Arena a = {0};
Arena a = {0}; // or arena_create(...) to specify a custom region
// capacity just for this arena
int *x = arena_alloc(&a, sizeof(*x) * 69);
float *y = arena_alloc(&a, sizeof(*y) * 420);
int *x = arena_alloc(&a, sizeof(*x) * 32);
float *y = arena_alloc(&a, sizeof(*y) * 512);
arena_free(&a);
arena_free(&a); // The arena can still be reused
return 0;
}
```

370
arena.h
View File

@@ -1,84 +1,200 @@
// arena.h - v1.1.3 - MIT License
// single header library for region-based memory management.
//
// [License and changelog]
//
// See end of file.
//
// [Single header library usage]
//
// Including this header file as such does what you normally expect.
//
// If you also need to include all of the function implementations you
// need to #define ARENA_IMPLEMENTATION before including the header file
// like this:
//
// #define ARENA_IMPLEMENTATION
// #include "arena.h"
//
// [Compile-time options]
//
// Note: every compile-time option listed here should be configured before
// the #include "arena.h"
//
// #define ARENA_REGION_CAPACITY new_region_capacity_in_bytes (4096)
//
// This macro defines the default capacity for arena regions.
//
// #define ARENA_ALIGNMENT alignment (8)
//
// This macro defines the memory alignment used for allocations.
//
// #define ARENA_NO_ASSERT
//
// This macro disables assertions that happen when allocations fail.
// The disabled assertions will be replaced with a simple condition
// that returns NULL when it fails. This macro affects every function
// that returns a pointer.
//
// #define ARENA_ASSERT my_assert
//
// This macro defines an alternative function for assertions. This has
// no effect when ARENA_NO_ASSERT is defined.
//
// #define ARENA_MALLOC my_malloc
// #define ARENA_FREE my_free
//
// These macros define alternative functions for dynamic allocation
// and deallocation. They are only used for managing Arena_Region
// structures. If redefined ensure that your functions consider memory
// alignment.
//
// [Function documentation]
//
// In this library, arenas are implemented as linked lists of regions. Each
// region will contain the allocated buffers. The following are all of the
// functions
//
// Arena arena_create(size_t region_capacity)
//
// This function is optional (see [Example] section): initializes an arena
// with a specified region capacity. It will override the default
// ARENA_REGION_CAPACITY.
//
// void arena_free(Arena *a)
//
// This function frees all of the regions allocated in the specified arena
// which invalidates all the pointers associated with the arena. The arena can
// still be reused. If the arena was created with arena_create() the
// configured region_capacity will be retained.
//
// void arena_reset(Arena *a)
//
// This function resets an arena by keeping all of the regions allocated but
// invalidates all of the pointers associated with the specified arena.
// Warning: this functions may cause fragmentation, consider setting an
// appropriate region capacity.
//
// void *arena_alloc(Arena *a, size_t size)
//
// This function allocates a buffer of <size> bytes into the specified arena
// and returns it's pointer.
//
// void *arena_copy(Arena *a, const void *src, size_t size);
//
// This function allocates a buffer of <size> bytes into the arena and copies
// the contents of <src>.
//
// char *arena_strdup(Arena *a, const char *s);
//
// This functions acts like the strdup() function but it instead allocates on
// the specified arena. It duplicates a string in the arena.
//
// [Notes]
//
// This library is not Thread-safe.
//
// [Example]
//
#if 0
#define ARENA_IMPLEMENTATION
#include "arena.h"
int main(void)
{
Arena a = {0}; // or arena_create(...) to specify a custom region
// capacity just for this arena
int *x = arena_alloc(&a, sizeof(*x) * 32);
float *y = arena_alloc(&a, sizeof(*y) * 512);
arena_free(&a); // The arena can still be reused
return 0;
}
#endif // [Example]
#ifndef ARENA_H_
#define ARENA_H_
#include <stdalign.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifndef ARENA_MIN_CAPACITY
#define ARENA_MIN_CAPACITY 4096
#endif // ARENA_MIN_CAPACITY
#ifndef ARENA_REGION_CAPACITY
# define ARENA_REGION_CAPACITY (8*1024)
#endif // ARENA_REGION_CAPACITY
#ifndef ARENA_ALIGNMENT
# define ARENA_ALIGNMENT alignof(max_align_t)
#endif // ARENA_ALIGNMENT
#ifndef ARENA_NO_ASSERT
# ifndef ARENA_ASSERT
# include <assert.h>
# define ARENA_ASSERT assert
# endif // ARENA_ASSERT
#else
# define ARENA_ASSERT(...) ((void)0)
#endif // ARENA_NO_ASSERT
#ifndef ARENA_MALLOC
# include <stdlib.h>
# define ARENA_MALLOC malloc
#endif // ARENA_MALLOC
#ifndef ARENA_FREE
# include <stdlib.h>
# define ARENA_FREE free
#endif // ARENA_FREE
#ifdef __cplusplus
extern "C" { // Prevent name mangling of functions
#endif // __cplusplus
typedef struct Arena_Region Arena_Region;
struct Arena_Region {
Arena_Region *next;
size_t count;
size_t capacity;
Arena_Region *next;
uint8_t data[];
alignas(ARENA_ALIGNMENT) uint8_t data[];
};
typedef struct {
typedef struct Arena {
Arena_Region *head;
Arena_Region *tail;
size_t region_capacity;
} Arena;
void *arena_alloc(Arena *a, size_t bytes);
// Arena management
Arena arena_create(size_t region_capacity);
void arena_free(Arena *a);
void arena_reset(Arena *a);
// Allocation other utilities
void *arena_alloc(Arena *a, size_t size);
void *arena_copy(Arena *a, const void *src, size_t size);
char *arena_strdup(Arena *a, const char *s);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // ARENA_H_
#ifdef ARENA_IMPLEMENTATION
void *arena_alloc(Arena *a, size_t bytes)
#ifdef __cplusplus
extern "C" { // Prevent name mangling of functions
#endif // __cplusplus
Arena arena_create(size_t region_capacity)
{
if (a == NULL) {
return NULL;
}
// Empty arena
if (a->head == NULL) {
size_t size = (bytes > ARENA_MIN_CAPACITY ? bytes : ARENA_MIN_CAPACITY);
a->head = (Arena_Region*)malloc(sizeof(*a->head) + size);
if (a->head == NULL) {
return NULL;
}
memset(a->head, 0, sizeof(*a->head));
a->head->count = bytes;
a->head->capacity = size;
a->tail = a->head;
return a->head->data;
}
// Not enough capacity
if (bytes > a->tail->capacity - a->tail->count) {
// Find first suitable region
while (a->tail->next != NULL && bytes > a->tail->capacity - a->tail->count) {
a->tail = a->tail->next;
}
// If found allocate on that region
if (bytes <= a->tail->capacity - a->tail->count) {
a->tail->count += bytes;
return a->tail->data + a->tail->count;
}
// If not create a new region
a->tail->next = (Arena_Region*)malloc(sizeof(*a->tail) + bytes);
if (a->tail->next == NULL) {
return NULL;
}
a->tail = a->tail->next;
memset(a->tail, 0, sizeof(*a->tail));
a->tail->count = bytes;
a->tail->capacity = bytes;
return a->tail->data;
}
a->tail->count += bytes;
return a->tail->data + a->tail->count;
Arena a;
memset(&a, 0, sizeof(a));
a.region_capacity = region_capacity;
return a;
}
void arena_free(Arena *a)
@@ -90,11 +206,13 @@ void arena_free(Arena *a)
Arena_Region *cur = a->head;
while (cur != NULL) {
Arena_Region *next = cur->next;
free(cur);
ARENA_FREE(cur);
cur = next;
}
memset(a, 0, sizeof(*a));
a->head = NULL;
a->tail = NULL;
// a->region_capacity = 0;
}
void arena_reset(Arena *a)
@@ -110,4 +228,144 @@ void arena_reset(Arena *a)
a->tail = a->head;
}
void *arena_alloc(Arena *a, size_t size)
{
if (a == NULL || size == 0) {
ARENA_ASSERT(false && "Invalid parameters");
return NULL;
}
// Ensure memory alignment of requested size
size = (size + (ARENA_ALIGNMENT - 1)) & ~(ARENA_ALIGNMENT - 1);
// Check for overflow
if (size > SIZE_MAX - sizeof(Arena_Region)) {
ARENA_ASSERT(false && "Requested size too large");
return NULL;
}
size_t region_capacity = (a->region_capacity == 0
? ARENA_REGION_CAPACITY : a->region_capacity);
// Calculate and check region allocation size
size_t alloc_size = (size > region_capacity ? size : region_capacity);
if (alloc_size > SIZE_MAX - sizeof(Arena_Region)) {
ARENA_ASSERT(false && "Region size overflow");
return NULL;
}
// Empty arena: allocate first region
if (a->head == NULL) {
a->head = (Arena_Region*)ARENA_MALLOC(sizeof(*a->head) + alloc_size);
if (a->head == NULL) {
ARENA_ASSERT(false && "Allocation failed");
return NULL;
}
a->head->next = NULL;
a->head->count = size;
a->head->capacity = alloc_size;
a->tail = a->head;
return a->head->data;
}
// Find first suitable region
Arena_Region *r = a->tail;
while (r != NULL && size > r->capacity - r->count) {
r = r->next;
}
// If found allocate on it
if (r != NULL) {
if (r->count > SIZE_MAX - size) {
ARENA_ASSERT(false && "Region count overflow");
return NULL;
}
r->count += size;
return r->data + r->count - size;
}
// If not found append a new region
a->tail->next = (Arena_Region*)ARENA_MALLOC(sizeof(*a->tail) + alloc_size);
if (a->tail->next == NULL) {
ARENA_ASSERT(false && "Allocation failed");
return NULL;
}
a->tail = a->tail->next;
a->tail->next = NULL;
a->tail->count = size;
a->tail->capacity = alloc_size;
return a->tail->data;
}
void *arena_copy(Arena *a, const void *src, size_t size)
{
if (a == NULL || src == NULL) {
ARENA_ASSERT(false && "Invalid parameters");
return NULL;
}
void *copy = arena_alloc(a, size);
if (copy == NULL) {
return NULL;
}
memcpy(copy, src, size);
return copy;
}
char *arena_strdup(Arena *a, const char *s)
{
if (a == NULL || s == NULL) {
ARENA_ASSERT(false && "Invalid parameters");
return NULL;
}
return (char*)arena_copy(a, s, strlen(s) + 1);
}
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // ARENA_IMPLEMENTATION
/*
* Revision history:
*
* 1.1.3 (2026-01-14) Align Arena_Region data flexible array member
* 1.1.2 (2026-01-10) Minor changes; check result of alloc in arena_copy()
* 1.1.1 (2025-11-18) Implement memory alignment; improve docs
* 1.1.0 (2025-11-18) New helper functions: arena_copy(), arena_strdup()
* 1.0.3 (2025-09-10) Renamed parameter bytes to size in arena_alloc()
* 1.0.2 (2025-09-06) Bug fixes; new ARENA_NO_ASSERT macro
* 1.0.1 (2025-08-02) Prevent name mangling of functions; don't reset
* region_capacity in arena_free()
* 1.0.0 (2025-07-24) Initial release
*/
/*
* MIT License
*
* Copyright (c) 2025 seajee
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/

41
test.c
View File

@@ -2,13 +2,12 @@
#include <stdlib.h>
#ifdef DEBUG
#define malloc(n) (printf("%s:%d:%s: malloc(%ld)\n",\
__FILE__, __LINE__, __func__, (n)), malloc((n)));
#define malloc(s) (printf("%s:%d:%s: malloc(%lu)\n",\
__FILE__, __LINE__, __func__, (s)), malloc((s)));
#define free(p) (printf("%s:%d:%s: free(%p)\n",\
__FILE__, __LINE__, __func__, (p)), free((p)));
#endif // DEBUG
#define ARENA_MIN_CAPACITY 400
#define ARENA_IMPLEMENTATION
#include "arena.h"
@@ -26,34 +25,28 @@ void arena_print(Arena arena)
int main(void)
{
printf("struct Arena_Region {\n");
printf(" Arena_Region *next; (%zu)\n", offsetof(struct Arena_Region, next));
printf(" size_t count; (%zu)\n", offsetof(struct Arena_Region, count));
printf(" size_t capacity; (%zu)\n", offsetof(struct Arena_Region, capacity));
printf(" uint8_t data[]; (%zu)\n", offsetof(struct Arena_Region, data));
printf("};\n");
printf("Alignment: %zu\n", ARENA_ALIGNMENT);
printf("================================================================\n");
Arena a = {0};
printf("------ small alloc ------\n");
arena_alloc(&a, 4012);
arena_alloc(&a, 100);
arena_alloc(&a, 100);
arena_alloc(&a, 100);
arena_alloc(&a, 100);
arena_print(a);
printf("\n=========================================================\n\n");
printf("------ big alloc ------\n");
arena_alloc(&a, 8000);
arena_print(a);
printf("\n=========================================================\n\n");
printf("------ reset ------\n");
arena_alloc(&a, 2301);
arena_alloc(&a, 4015);
arena_alloc(&a, 10000);
arena_reset(&a);
arena_print(a);
printf("\n=========================================================\n\n");
printf("------ allocs after reset ------\n");
arena_alloc(&a, 1000);
arena_alloc(&a, 300);
arena_alloc(&a, 400);
arena_alloc(&a, 9000);
arena_print(a);
arena_free(&a);