{"id":42154979,"url":"https://github.com/choco-technologies/dmheap","last_synced_at":"2026-01-26T19:06:04.945Z","repository":{"id":321632203,"uuid":"1084169334","full_name":"choco-technologies/dmheap","owner":"choco-technologies","description":"DMOD Heap ","archived":false,"fork":false,"pushed_at":"2025-11-20T11:55:59.000Z","size":152,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-11-20T13:15:34.296Z","etag":null,"topics":["dmod","free","malloc","staticlibrary"],"latest_commit_sha":null,"homepage":"","language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/choco-technologies.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-27T10:15:45.000Z","updated_at":"2025-11-20T11:56:02.000Z","dependencies_parsed_at":null,"dependency_job_id":"063cec20-e609-4f32-84c4-a592d82d5553","html_url":"https://github.com/choco-technologies/dmheap","commit_stats":null,"previous_names":["choco-technologies/dmheap"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/choco-technologies/dmheap","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/choco-technologies%2Fdmheap","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/choco-technologies%2Fdmheap/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/choco-technologies%2Fdmheap/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/choco-technologies%2Fdmheap/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/choco-technologies","download_url":"https://codeload.github.com/choco-technologies/dmheap/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/choco-technologies%2Fdmheap/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28785172,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-26T13:55:28.044Z","status":"ssl_error","status_checked_at":"2026-01-26T13:55:26.068Z","response_time":59,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dmod","free","malloc","staticlibrary"],"created_at":"2026-01-26T19:02:41.573Z","updated_at":"2026-01-26T19:06:04.893Z","avatar_url":"https://github.com/choco-technologies.png","language":"C","funding_links":[],"categories":[],"sub_categories":[],"readme":"# dmheap - DMOD Heap Memory Manager\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n\nA sophisticated, module-aware heap memory manager designed specifically for the **DMOD (Dynamic Modules)** framework. dmheap provides dynamic memory allocation with module tracking, alignment support, and efficient memory management for embedded systems.\n\n## Table of Contents\n\n- [Overview](#overview)\n- [What is DMOD?](#what-is-dmod)\n- [What is dmheap?](#what-is-dmheap)\n- [Architecture](#architecture)\n- [Features](#features)\n- [Building](#building)\n- [Testing](#testing)\n- [Usage](#usage)\n- [Integration Example](#integration-example)\n- [API Reference](#api-reference)\n- [Configuration Options](#configuration-options)\n- [Contributing](#contributing)\n- [License](#license)\n\n## Overview\n\ndmheap is a custom heap memory allocator that integrates seamlessly with the DMOD dynamic module system. It provides module-aware memory management, allowing you to track which modules own which memory blocks, automatically clean up module memory, and efficiently manage memory in embedded systems with limited resources.\n\n## What is DMOD?\n\n**DMOD (Dynamic Modules)** is a library that enables dynamic loading and unloading of modules in embedded systems at runtime. It allows you to:\n\n- **Dynamically load modules**: Load functionality from `.dmf` files without recompiling\n- **Manage dependencies**: Automatically handle module dependencies\n- **Inter-module communication**: Modules can communicate via a common API\n- **Resource management**: Efficiently manage system resources\n- **Safe updates**: Update individual modules without affecting the entire system\n\nDMOD provides a modular architecture that makes embedded systems more flexible, maintainable, and easier to extend. For more information, visit the [DMOD repository](https://github.com/choco-technologies/dmod).\n\n## What is dmheap?\n\n**dmheap** is a heap memory manager specifically designed to work with DMOD. It provides:\n\n- **Module-aware allocation**: Track which module owns each memory allocation\n- **Automatic cleanup**: When a module is unloaded, all its allocations are freed automatically\n- **Alignment support**: Allocate memory with specific alignment requirements (critical for embedded systems)\n- **Fragmentation management**: Tools to concatenate free blocks and reduce fragmentation\n- **Static buffer management**: Operates on a pre-allocated buffer (no reliance on system malloc)\n- **Thread-safe operations**: Uses DMOD's critical section mechanisms\n\ndmheap can optionally provide implementations for DMOD's core memory allocation API (`Dmod_MallocEx`, `Dmod_FreeEx`, etc.), making it a complete memory management solution for DMOD-based systems.\n\n## Architecture\n\n### Memory Block Structure\n\ndmheap manages memory using a linked-list based approach with two main lists:\n\n```\n┌─────────────────────────────────────────────────┐\n│            dmheap Context                       │\n├─────────────────────────────────────────────────┤\n│  - heap_start: void*                            │\n│  - heap_size: size_t                            │\n│  - alignment: size_t                            │\n│  - free_list: block_t*  ───────┐               │\n│  - used_list: block_t*  ───┐   │               │\n│  - module_list: module_t*   │   │               │\n└────────────────────────────┼───┼───────────────┘\n                             │   │\n                ┌────────────┘   └──────────────┐\n                ▼                                ▼\n          ┌──────────┐                    ┌──────────┐\n          │ Used     │                    │ Free     │\n          │ Block 1  │──►Block 2──►...    │ Block 1  │──►Block 2\n          └──────────┘                    └──────────┘\n```\n\nEach memory block contains:\n- **next**: Pointer to the next block in the list\n- **address**: Pointer to the usable memory\n- **size**: Size of the usable memory\n- **owner**: Pointer to the owning module (for tracking)\n\n### Module Tracking\n\ndmheap maintains a list of registered modules. Each allocation can be associated with a module, enabling:\n\n1. **Automatic cleanup**: When `dmheap_unregister_module()` is called, all memory allocated by that module is automatically freed\n2. **Memory tracking**: Know which module is using how much memory\n3. **Safe module unloading**: Prevent memory leaks when modules are unloaded\n\n### Alignment Handling\n\ndmheap supports custom alignment for allocations, which is crucial for:\n- DMA operations requiring aligned buffers\n- SIMD operations (SSE, NEON, etc.)\n- Hardware-specific alignment requirements\n- Performance optimization\n\n## Features\n\n- ✅ **Module-aware allocations**: Track ownership of memory by modules\n- ✅ **Automatic module cleanup**: Free all module memory on unregister\n- ✅ **Custom alignment support**: Allocate memory with specific alignment\n- ✅ **Memory reallocation**: Efficient realloc implementation\n- ✅ **Fragmentation management**: Concatenate free blocks to reduce fragmentation\n- ✅ **Static buffer operation**: No dependency on system malloc/free\n- ✅ **Thread-safe**: Uses DMOD critical sections for synchronization\n- ✅ **Comprehensive logging**: Integration with DMOD logging system\n- ✅ **Zero external dependencies**: Only requires DMOD framework\n- ✅ **Optional DMOD API implementation**: Can provide standard DMOD memory functions\n\n## Building\n\n### Prerequisites\n\n- **CMake**: Version 3.10 or higher\n- **C Compiler**: GCC or compatible\n- **Make**: For Makefile-based builds (optional)\n\n### Using CMake\n\n```bash\n# Clone the repository\ngit clone https://github.com/choco-technologies/dmheap.git\ncd dmheap\n\n# Create build directory\nmkdir build\ncd build\n\n# Configure\ncmake ..\n\n# Build\nmake\n\n# Run tests\nctest --verbose\n```\n\n### Build Options\n\nYou can customize the build with these CMake options:\n\n```bash\n# Disable DMOD API implementation (see Configuration Options below)\ncmake -DDMHEAP_DONT_IMPLEMENT_DMOD_API=ON ..\n\n# Disable tests\ncmake -DBUILD_TESTS=OFF ..\n\n# Change DMOD mode\ncmake -DDMOD_MODE=DMOD_EMBEDDED ..\n```\n\n### Using Makefile\n\ndmheap also supports traditional Makefile builds:\n\n```bash\n# Build the library\nmake\n\n# The library will be created as libdmheap.a\n```\n\nThe Makefile is automatically generated by CMake and includes necessary DMOD paths.\n\n## Testing\n\ndmheap includes comprehensive test suites:\n\n### Test Suites\n\n1. **dmheap_unit**: Unit tests for core functionality\n   - Initialization\n   - Module registration\n   - Basic allocation/deallocation\n   - Aligned allocations\n   - Reallocation\n   - Fragmentation handling\n   - Stress tests\n\n2. **dmheap_module**: Module-level integration tests\n   - FileSystem simulation\n   - Network buffer pool\n   - Multi-module usage\n   - Dynamic data structures\n   - Memory reuse patterns\n   - Alignment requirements\n\n3. **simple_test**: Basic smoke tests\n\n### Running Tests\n\n```bash\n# Run all tests\ncd build\nctest\n\n# Run with verbose output\nctest --verbose\n\n# Run specific test\n./tests/test_dmheap_unit\n./tests/test_dmheap_module\n./tests/test_simple\n```\n\n### Example Test Output\n\n```\n=== Simple DMHEAP Test ===\n[INFO] dmheap: Initialized with buffer 0x7ffd... of size 65536.\nInit: PASS\nIs Initialized: PASS\nMalloc: PASS\nWrite: PASS\nFree: PASS\n\nAll simple tests completed!\n```\n\n## Usage\n\n### Basic Usage\n\n```c\n#include \"dmheap.h\"\n#include \u003cstring.h\u003e\n\n// 1. Define your heap buffer\n#define HEAP_SIZE (64 * 1024)  // 64KB\nstatic char heap_buffer[HEAP_SIZE];\n\nint main(void) {\n    // 2. Initialize the heap (returns a context)\n    dmheap_context_t* ctx = dmheap_init(heap_buffer, HEAP_SIZE, 8);  // 8-byte alignment\n    if (ctx == NULL) {\n        // Handle initialization failure\n        return -1;\n    }\n    \n    // 3. Set as default context (optional - allows using NULL in API calls)\n    dmheap_set_default_context(ctx);\n    \n    // 4. Allocate memory (NULL uses default context)\n    void* ptr = dmheap_malloc(NULL, 256, \"main\");\n    if (ptr != NULL) {\n        // Use the memory\n        memset(ptr, 0, 256);\n        \n        // 5. Free memory\n        dmheap_free(NULL, ptr, false);\n    }\n    \n    return 0;\n}\n```\n\n### Module-Aware Usage\n\n```c\n#include \"dmheap.h\"\n\nvoid module_example(void) {\n    // Register a module (NULL uses default context)\n    dmheap_register_module(NULL, \"my_module\");\n    \n    // Allocate memory for this module\n    void* data1 = dmheap_malloc(NULL, 512, \"my_module\");\n    void* data2 = dmheap_malloc(NULL, 1024, \"my_module\");\n    \n    // Use the memory...\n    \n    // When done with the module, unregister it\n    // This automatically frees ALL memory allocated by \"my_module\"\n    dmheap_unregister_module(NULL, \"my_module\");\n    // data1 and data2 are now freed automatically!\n}\n```\n\n### Multiple Independent Contexts\n\nOne of the key features of the context-oriented design is the ability to create multiple independent heaps for different purposes:\n\n```c\n#include \"dmheap.h\"\n#include \u003cstring.h\u003e\n\n// Example: Separate heaps for kernel and external RAM\n#define KERNEL_HEAP_SIZE (128 * 1024)  // 128KB for kernel\n#define EXTRAM_HEAP_SIZE (1024 * 1024) // 1MB for external RAM\n\nstatic char kernel_heap_buffer[KERNEL_HEAP_SIZE];\nstatic char extram_heap_buffer[EXTRAM_HEAP_SIZE];\n\nvoid multi_context_example(void) {\n    // Create separate contexts for different memory regions\n    dmheap_context_t* kernel_ctx = dmheap_init(kernel_heap_buffer, KERNEL_HEAP_SIZE, 8);\n    dmheap_context_t* extram_ctx = dmheap_init(extram_heap_buffer, EXTRAM_HEAP_SIZE, 32);\n    \n    // Set kernel context as default (optional)\n    dmheap_set_default_context(kernel_ctx);\n    \n    // Allocate kernel data from kernel heap (NULL uses default)\n    void* kernel_data = dmheap_malloc(NULL, 1024, \"kernel\");\n    \n    // Allocate large buffers from external RAM (explicitly specify context)\n    void* large_buffer = dmheap_malloc(extram_ctx, 512 * 1024, \"video\");\n    \n    // Each context maintains its own free/used lists\n    // and can have different alignment requirements\n    \n    // Clean up\n    dmheap_free(NULL, kernel_data, false);           // Uses default (kernel_ctx)\n    dmheap_free(extram_ctx, large_buffer, false);    // Explicitly use extram_ctx\n}\n```\n\n**Benefits of Multiple Contexts:**\n- Separate memory pools for different purposes (kernel, external RAM, DMA buffers)\n- Different alignment requirements per context\n- Independent memory management and tracking\n- Isolation between different subsystems\n\n### Aligned Allocation\n\n```c\n#include \"dmheap.h\"\n#include \u003cassert.h\u003e\n#include \u003cstdint.h\u003e\n\nvoid aligned_example(void) {\n    // Allocate 1KB with 64-byte alignment (for DMA, SIMD, etc.)\n    void* aligned_buffer = dmheap_aligned_alloc(NULL, 64, 1024, \"dma_module\");\n    \n    // Verify alignment\n    assert((uintptr_t)aligned_buffer % 64 == 0);\n    \n    // Use the buffer...\n    \n    // Free when done\n    dmheap_free(NULL, aligned_buffer, true);  // true = concatenate free blocks\n}\n```\n\n### Memory Reallocation\n\n```c\n#include \"dmheap.h\"\n\nvoid realloc_example(void) {\n    // Initial allocation\n    void* buffer = dmheap_malloc(NULL, 100, \"data_processor\");\n    memcpy(buffer, \"Hello\", 6);\n    \n    // Need more space\n    buffer = dmheap_realloc(NULL, buffer, 200, \"data_processor\");\n    // Original data is preserved, now have 200 bytes\n    \n    // Need less space\n    buffer = dmheap_realloc(NULL, buffer, 50, \"data_processor\");\n    // Data preserved, memory reduced\n    \n    dmheap_free(NULL, buffer, false);\n}\n```\n\n### Fragmentation Management\n\n```c\n#include \"dmheap.h\"\n\nvoid fragmentation_example(void) {\n    // Allocate and free in a pattern that creates fragmentation\n    void* a = dmheap_malloc(NULL, 100, \"test\");\n    void* b = dmheap_malloc(NULL, 100, \"test\");\n    void* c = dmheap_malloc(NULL, 100, \"test\");\n    \n    dmheap_free(NULL, b, false);  // Creates a hole in the middle\n    \n    // Manually concatenate all free blocks to reduce fragmentation\n    dmheap_concatenate_free_blocks(NULL);\n    \n    // Or use concatenate parameter when freeing\n    dmheap_free(NULL, a, true);  // Automatically tries to merge with adjacent free blocks\n    dmheap_free(NULL, c, true);\n}\n```\n\n## Integration Example\n\nHere's a complete example of integrating dmheap into a DMOD-based embedded project:\n\n### Project Structure\n\n```\nmy_embedded_project/\n├── CMakeLists.txt\n├── main.c\n├── modules/\n│   ├── sensor_module/\n│   └── network_module/\n└── lib/\n    └── dmheap/  (this repository)\n```\n\n### CMakeLists.txt\n\n```cmake\ncmake_minimum_required(VERSION 3.10)\nproject(my_embedded_project C)\n\n# Add dmheap as a subdirectory\nadd_subdirectory(lib/dmheap)\n\n# Your main executable\nadd_executable(my_app main.c)\n\n# Link with dmheap\ntarget_link_libraries(my_app PRIVATE dmheap)\n```\n\n### main.c\n\n```c\n#include \"dmheap.h\"\n#include \"dmod.h\"\n#include \u003cstdio.h\u003e\n#include \u003cstring.h\u003e\n#include \u003cstdint.h\u003e\n\n// Define heap for the entire system\n#define SYSTEM_HEAP_SIZE (256 * 1024)  // 256KB\nstatic char system_heap[SYSTEM_HEAP_SIZE];\n\n// Simulated sensor module\nvoid sensor_module_init(void) {\n    dmheap_register_module(NULL, \"sensor\");\n    \n    // Allocate sensor data buffer\n    typedef struct {\n        float temperature;\n        float humidity;\n        uint32_t timestamp;\n    } sensor_data_t;\n    \n    sensor_data_t* data = dmheap_malloc(NULL, sizeof(sensor_data_t), \"sensor\");\n    if (data != NULL) {\n        data-\u003etemperature = 25.5f;\n        data-\u003ehumidity = 60.0f;\n        data-\u003etimestamp = 12345;\n        \n        printf(\"Sensor module initialized with data at %p\\n\", data);\n        // Note: In real code, you'd store this pointer for later use\n    }\n}\n\nvoid sensor_module_cleanup(void) {\n    // Automatically frees all sensor module allocations\n    dmheap_unregister_module(NULL, \"sensor\");\n    printf(\"Sensor module cleaned up\\n\");\n}\n\n// Simulated network module\nvoid network_module_init(void) {\n    dmheap_register_module(NULL, \"network\");\n    \n    // Allocate network buffers (need DMA alignment)\n    #define NUM_NET_BUFFERS 10\n    #define NET_BUFFER_SIZE 1500  // MTU size\n    \n    for (int i = 0; i \u003c NUM_NET_BUFFERS; i++) {\n        void* buffer = dmheap_aligned_alloc(NULL, 64, NET_BUFFER_SIZE, \"network\");\n        if (buffer == NULL) {\n            printf(\"Failed to allocate network buffer %d\\n\", i);\n            break;\n        }\n        // In real code, you'd store these pointers in a buffer pool\n    }\n    \n    printf(\"Network module initialized with %d buffers\\n\", NUM_NET_BUFFERS);\n}\n\nvoid network_module_cleanup(void) {\n    // Automatically frees all network module allocations\n    dmheap_unregister_module(NULL, \"network\");\n    printf(\"Network module cleaned up\\n\");\n}\n\nint main(void) {\n    printf(\"=== Embedded System with dmheap ===\\n\\n\");\n    \n    // Initialize heap for the entire system\n    dmheap_context_t* ctx = dmheap_init(system_heap, SYSTEM_HEAP_SIZE, 8);\n    if (ctx == NULL) {\n        printf(\"ERROR: Failed to initialize heap\\n\");\n        return -1;\n    }\n    dmheap_set_default_context(ctx);  // Set as default for NULL context calls\n    printf(\"Heap initialized: %d KB\\n\\n\", SYSTEM_HEAP_SIZE / 1024);\n    \n    // Initialize modules\n    sensor_module_init();\n    network_module_init();\n    \n    printf(\"\\n--- Modules running ---\\n\");\n    printf(\"Both modules are using heap memory...\\n\");\n    \n    // Simulate running for a while\n    printf(\"\\n--- Shutting down sensor module ---\\n\");\n    sensor_module_cleanup();\n    \n    printf(\"\\n--- Network module still running ---\\n\");\n    printf(\"Network module continues to function...\\n\");\n    \n    // Clean up everything\n    printf(\"\\n--- System shutdown ---\\n\");\n    network_module_cleanup();\n    \n    printf(\"\\nAll modules cleaned up successfully!\\n\");\n    \n    return 0;\n}\n```\n\n### Build and Run\n\n```bash\nmkdir build \u0026\u0026 cd build\ncmake ..\nmake\n./my_app\n```\n\n### Expected Output\n\n```\n=== Embedded System with dmheap ===\n\nHeap initialized: 256 KB\n\n[INFO] dmheap: Initialized with buffer 0x... of size 262144.\n[INFO] dmheap: Module sensor registered successfully.\nSensor module initialized with data at 0x...\n[INFO] dmheap: Module network registered successfully.\nNetwork module initialized with 10 buffers\n\n--- Modules running ---\nBoth modules are using heap memory...\n\n--- Shutting down sensor module ---\n[INFO] dmheap: Module sensor unregistered successfully.\nSensor module cleaned up\n\n--- Network module still running ---\nNetwork module continues to function...\n\n--- System shutdown ---\n[INFO] dmheap: Module network unregistered successfully.\nNetwork module cleaned up\n\nAll modules cleaned up successfully!\n```\n\n## API Reference\n\n### Initialization\n\n#### `dmheap_init`\n\n```c\ndmheap_context_t* dmheap_init(void* buffer, size_t size, size_t alignment);\n```\n\nInitialize the heap with a given buffer and size. The context structure is stored at the beginning of the provided buffer.\n\n- **Parameters:**\n  - `buffer`: Pointer to the memory buffer to be used as heap\n  - `size`: Size of the memory buffer in bytes (must be large enough for context + data)\n  - `alignment`: Default alignment for allocations (must be power of 2)\n- **Returns:** Pointer to the heap context, or `NULL` if initialization fails\n- **Thread-safe:** Yes\n- **Note:** The first initialized context automatically becomes the default context\n\n#### `dmheap_set_default_context`\n\n```c\nvoid dmheap_set_default_context(dmheap_context_t* ctx);\n```\n\nSet the default heap context to use when `NULL` is passed to API functions.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context to set as default\n- **Thread-safe:** Yes\n\n#### `dmheap_get_default_context`\n\n```c\ndmheap_context_t* dmheap_get_default_context(void);\n```\n\nGet the default heap context.\n\n- **Returns:** Pointer to the default heap context, or `NULL` if not set\n- **Thread-safe:** Yes\n\n#### `dmheap_is_initialized`\n\n```c\nbool dmheap_is_initialized(dmheap_context_t* ctx);\n```\n\nCheck if the heap context is initialized.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n- **Returns:** `true` if initialized, `false` otherwise\n- **Thread-safe:** Yes\n\n### Module Management\n\n#### `dmheap_register_module`\n\n```c\nbool dmheap_register_module(dmheap_context_t* ctx, const char* module_name);\n```\n\nRegister a module with the heap for memory tracking.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n  - `module_name`: Name of the module to register (max length: `DMOD_MAX_MODULE_NAME_LENGTH`)\n- **Returns:** `true` if registration is successful, `false` otherwise\n- **Thread-safe:** Yes\n\n#### `dmheap_unregister_module`\n\n```c\nvoid dmheap_unregister_module(dmheap_context_t* ctx, const char* module_name);\n```\n\nUnregister a module from the heap and automatically free all its allocations.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n  - `module_name`: Name of the module to unregister\n- **Thread-safe:** Yes\n- **Note:** This automatically frees ALL memory allocated by this module\n\n### Memory Allocation\n\n#### `dmheap_malloc`\n\n```c\nvoid* dmheap_malloc(dmheap_context_t* ctx, size_t size, const char* module_name);\n```\n\nAllocate memory from the heap.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n  - `size`: Size of memory to allocate in bytes\n  - `module_name`: Name of the module requesting allocation (for tracking, can be NULL)\n- **Returns:** Pointer to the allocated memory, or NULL if allocation fails\n- **Thread-safe:** Yes\n- **Alignment:** Uses default alignment specified during `dmheap_init`\n\n#### `dmheap_aligned_alloc`\n\n```c\nvoid* dmheap_aligned_alloc(dmheap_context_t* ctx, size_t alignment, size_t size, const char* module_name);\n```\n\nAllocate aligned memory from the heap.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n  - `alignment`: Alignment requirement (must be power of 2)\n  - `size`: Size of memory to allocate in bytes\n  - `module_name`: Name of the module requesting allocation (for tracking, can be NULL)\n- **Returns:** Pointer to the allocated memory (aligned to `alignment`), or NULL if allocation fails\n- **Thread-safe:** Yes\n- **Use cases:** DMA buffers, SIMD operations, hardware requirements\n\n#### `dmheap_realloc`\n\n```c\nvoid* dmheap_realloc(dmheap_context_t* ctx, void* ptr, size_t size, const char* module_name);\n```\n\nReallocate memory from the heap.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n  - `ptr`: Pointer to previously allocated memory (can be NULL)\n  - `size`: New size of memory to allocate in bytes\n  - `module_name`: Name of the module requesting reallocation (for logging)\n- **Returns:** Pointer to the reallocated memory, or NULL if reallocation fails\n- **Thread-safe:** Yes\n- **Behavior:**\n  - If `ptr` is NULL, behaves like `dmheap_malloc`\n  - If `size` is smaller, shrinks the allocation\n  - If `size` is larger, allocates new memory and copies data\n  - Original data is preserved up to the minimum of old and new sizes\n\n#### `dmheap_free`\n\n```c\nvoid dmheap_free(dmheap_context_t* ctx, void* ptr, bool concatenate);\n```\n\nFree memory back to the heap.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n  - `ptr`: Pointer to the memory to free\n  - `concatenate`: If `true`, attempt to merge adjacent free blocks to reduce fragmentation\n- **Thread-safe:** Yes\n- **Note:** Safe to call with NULL pointer (no-op)\n\n### Fragmentation Management\n\n#### `dmheap_concatenate_free_blocks`\n\n```c\nvoid dmheap_concatenate_free_blocks(dmheap_context_t* ctx);\n```\n\nManually concatenate all adjacent free blocks in the heap to reduce fragmentation.\n\n- **Parameters:**\n  - `ctx`: Pointer to the heap context (`NULL` to use default context)\n- **Thread-safe:** Yes\n- **Use case:** Call periodically or when you need to allocate large contiguous blocks\n\n## Configuration Options\n\n### `DMHEAP_DONT_IMPLEMENT_DMOD_API`\n\nThis is a CMake option and preprocessor definition that controls whether dmheap provides implementations for DMOD's standard memory allocation API.\n\n#### What it does:\n\nWhen **NOT defined** (default behavior):\n- dmheap implements these DMOD API functions:\n  - `Dmod_MallocEx` → calls `dmheap_aligned_alloc`\n  - `Dmod_ReallocEx` → calls `dmheap_realloc`\n  - `Dmod_AlignedMallocEx` → calls `dmheap_aligned_alloc`\n  - `Dmod_FreeEx` → calls `dmheap_free`\n  - `Dmod_FreeModule` → calls `dmheap_unregister_module`\n\nWhen **defined**:\n- dmheap does NOT implement these functions\n- You must provide your own implementations elsewhere in your project\n- dmheap only provides its own `dmheap_*` functions\n\n#### Why use it?\n\n**Use `DMHEAP_DONT_IMPLEMENT_DMOD_API=ON` when:**\n\n1. **You have another memory allocator**: If you want to use a different allocator for DMOD's memory functions\n2. **Custom memory management**: You need custom implementations of the DMOD memory API\n3. **Multiple memory heaps**: You're using dmheap for specific purposes but have another allocator for general use\n4. **Static linking conflicts**: You're linking multiple libraries that might provide DMOD API implementations\n\n**Use default (OFF) when:**\n\n1. **Simple integration**: You want dmheap to handle all DMOD memory allocation\n2. **Single allocator**: dmheap is your only memory allocator\n3. **Quick setup**: You want minimal configuration\n\n#### Example usage:\n\n**CMake:**\n```bash\n# Enable the option\ncmake -DDMHEAP_DONT_IMPLEMENT_DMOD_API=ON ..\n\n# Or in CMakeLists.txt\nset(DMHEAP_DONT_IMPLEMENT_DMOD_API ON CACHE BOOL \"Don't implement DMOD API\")\n```\n\n**Source code:**\n```c\n// If you want to provide your own implementations\n#define DMHEAP_DONT_IMPLEMENT_DMOD_API\n#include \"dmheap.h\"\n\n// Now you must implement these yourself:\nDMOD_INPUT_API_DECLARATION(Dmod, 1.0, void*, _MallocEx, (size_t Size, const char* ModuleName)) {\n    // Your custom implementation\n    return my_custom_malloc(Size);\n}\n\n// ... implement other DMOD memory functions\n```\n\n#### Implementation details:\n\nIn `dmheap.c`, the DMOD API implementations are conditionally compiled:\n\n```c\n#ifndef DMHEAP_DONT_IMPLEMENT_DMOD_API\nDMOD_INPUT_API_DECLARATION(Dmod, 1.0, void*, _MallocEx, ( size_t Size, const char* ModuleName ))\n{\n    return dmheap_aligned_alloc( g_dmheap_context.alignment, Size, ModuleName );\n}\n\n// ... other DMOD API implementations\n#endif // DMHEAP_DONT_IMPLEMENT_DMOD_API\n```\n\nThis allows you to:\n- Use dmheap as a standalone heap manager with its own API\n- Integrate with DMOD without conflicts\n- Provide custom DMOD memory implementations if needed\n\n## Contributing\n\nContributions are welcome! Please feel free to submit issues, fork the repository, and create pull requests.\n\n### Development Setup\n\n1. Fork the repository\n2. Clone your fork: `git clone https://github.com/YOUR_USERNAME/dmheap.git`\n3. Create a feature branch: `git checkout -b feature/my-new-feature`\n4. Make your changes and add tests\n5. Run tests: `cd build \u0026\u0026 ctest`\n6. Commit your changes: `git commit -am 'Add some feature'`\n7. Push to the branch: `git push origin feature/my-new-feature`\n8. Submit a pull request\n\n### Code Style\n\n- Follow the existing code style\n- Use meaningful variable and function names\n- Add comments for complex logic\n- Update documentation for API changes\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n```\nMIT License\n\nCopyright (c) 2025 Choco-Technologies\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n## Acknowledgments\n\n- [DMOD (Dynamic Modules)](https://github.com/choco-technologies/dmod) - The dynamic module loading framework\n- Choco-Technologies team for creating and maintaining this project\n\n## Related Projects\n\n- [DMOD](https://github.com/choco-technologies/dmod) - Dynamic Module Loading Framework\n- [DMOD Examples](https://github.com/choco-technologies/dmod/tree/develop/examples) - Example projects using DMOD\n\n---\n\n**For more information and support, please visit the [dmheap repository](https://github.com/choco-technologies/dmheap) or contact the Choco-Technologies team.** \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchoco-technologies%2Fdmheap","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchoco-technologies%2Fdmheap","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchoco-technologies%2Fdmheap/lists"}