You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
2.0 KiB
49 lines
2.0 KiB
// memory_pool.h |
|
#ifndef MEMORY_POOL_H |
|
#define MEMORY_POOL_H |
|
|
|
#ifdef __cplusplus |
|
extern "C" { |
|
#endif |
|
|
|
|
|
#include <stddef.h> |
|
#include "debug_config.h" |
|
|
|
#define MEMORY_POOL_MAX_FREE 64 |
|
|
|
#define XSTR(s) STR(s) |
|
#define STR(s) #s |
|
#define PLOCATION __FILE__ ":" XSTR(__LINE__) "[POOL]" |
|
|
|
struct memory_pool { |
|
void* free_head; // Голова linked list свободных блоков (next хранится в начале каждого блока) |
|
int free_count; // Количество свободных блоков |
|
size_t object_size; // Размер объектов в пуле (пользовательские данные) |
|
size_t allocations; // Общее количество аллокаций (включая новые malloc) |
|
size_t reuse_count; // Количество повторных использований из пула |
|
uint8_t alloc_tag_counter; // монотонный счётчик для детекции double-free (1 байт) |
|
const char* name; // Имя пула для диагностики (напр. "data_pool", "pkt_pool") |
|
}; |
|
|
|
// сам пул: |
|
// если используем с элементами ll_queue то не забываем что к object_size надо прибавить sizeof(struct ll_entry) |
|
struct memory_pool* memory_pool_init(size_t object_size, const char* name); |
|
void memory_pool_destroy(struct memory_pool* pool); |
|
|
|
// элементы пула: |
|
void* memory_pool_alloc_impl(struct memory_pool* pool, const char* location); |
|
void memory_pool_free_impl(struct memory_pool* pool, void* obj, const char* location); |
|
void memory_pool_get_stats(struct memory_pool* pool, size_t* allocations, size_t* reuse_count); |
|
size_t memory_pool_get_total_free_blocks(void); |
|
|
|
#define memory_pool_alloc(pool) memory_pool_alloc_impl(pool, PLOCATION) |
|
#define memory_pool_free(pool, obj) memory_pool_free_impl(pool, obj, PLOCATION) |
|
|
|
int memory_pool_is_freed(struct memory_pool* pool, void* obj); |
|
|
|
|
|
#ifdef __cplusplus |
|
} |
|
#endif |
|
#endif // MEMORY_POOL_H
|
|
|