<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ajay Roy </title>
    <description>The latest articles on DEV Community by Ajay Roy  (@linuslover).</description>
    <link>https://dev.to/linuslover</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3339217%2Fa0010b46-a837-4749-9aa0-161b15395359.png</url>
      <title>DEV Community: Ajay Roy </title>
      <link>https://dev.to/linuslover</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/linuslover"/>
    <language>en</language>
    <item>
      <title>Memory management system in C/C++</title>
      <dc:creator>Ajay Roy </dc:creator>
      <pubDate>Mon, 06 Oct 2025 04:13:23 +0000</pubDate>
      <link>https://dev.to/linuslover/memory-management-system-in-cc-5dl9</link>
      <guid>https://dev.to/linuslover/memory-management-system-in-cc-5dl9</guid>
      <description>&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;h1&gt;
  
  
  include 
&lt;/h1&gt;

&lt;p&gt;// ----------------------&lt;br&gt;
// High-Performance Enterprise Memory Manager&lt;br&gt;
// ----------------------&lt;br&gt;
class HPMemoryManager {&lt;br&gt;
private:&lt;br&gt;
    // Global tracking of allocations&lt;br&gt;
    std::unordered_set allocations;&lt;br&gt;
    std::unordered_set persistentAllocations;&lt;br&gt;
    mutable std::shared_mutex allocMutex;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Lock-free / thread-local arenas
struct ArenaBlock {
    std::atomic&amp;lt;ArenaBlock*&amp;gt; next;
    char data[1]; // flexible array
};

struct Arena {
    size_t blockSize;
    std::atomic&amp;lt;ArenaBlock*&amp;gt; freeListHead;
    size_t totalBlocks;
    std::mutex expandMutex; // only for pool expansion
};

std::unordered_map&amp;lt;size_t, std::shared_ptr&amp;lt;Arena&amp;gt;&amp;gt; globalArenas;

// Thread-local arena access
thread_local static std::unordered_map&amp;lt;size_t, std::shared_ptr&amp;lt;Arena&amp;gt;&amp;gt; threadLocalArenas;
thread_local static std::unordered_set&amp;lt;void*&amp;gt; threadLocalAllocations;

bool productionBoundsCheck = true;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;public:&lt;br&gt;
    HPMemoryManager() = default;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// ----------------------
// Lock-free allocation from arena
// ----------------------
void* allocate(size_t size, bool persistent = false) {
    ArenaBlock* block = nullptr;

    auto&amp;amp; arena = getOrCreateArena(size);

    // Try pop from lock-free free list
    while (true) {
        block = arena-&amp;gt;freeListHead.load(std::memory_order_acquire);
        if (!block) break;
        ArenaBlock* next = block-&amp;gt;next.load(std::memory_order_relaxed);
        if (arena-&amp;gt;freeListHead.compare_exchange_weak(block, next)) {
            registerAllocation(block-&amp;gt;data, persistent);
            return block-&amp;gt;data;
        }
    }

    // Expand pool if empty
    std::lock_guard&amp;lt;std::mutex&amp;gt; lock(arena-&amp;gt;expandMutex);
    size_t expandCount = 128; // batch allocate
    for (size_t i = 0; i &amp;lt; expandCount; ++i) {
        char* raw = new char[size + sizeof(ArenaBlock*)];
        auto* newBlock = reinterpret_cast&amp;lt;ArenaBlock*&amp;gt;(raw);
        newBlock-&amp;gt;next.store(arena-&amp;gt;freeListHead.load());
        arena-&amp;gt;freeListHead.store(newBlock);
    }

    return allocate(size, persistent);
}

void deallocate(void* ptr, size_t size) {
    if (!ptr) return;
    unregisterAllocation(ptr);

    auto&amp;amp; arena = getOrCreateArena(size);
    auto* block = reinterpret_cast&amp;lt;ArenaBlock*&amp;gt;(
        reinterpret_cast&amp;lt;char*&amp;gt;(ptr) - offsetof(ArenaBlock, data)
    );

    // push back lock-free
    ArenaBlock* oldHead = arena-&amp;gt;freeListHead.load();
    do {
        block-&amp;gt;next.store(oldHead);
    } while (!arena-&amp;gt;freeListHead.compare_exchange_weak(oldHead, block));
}

template&amp;lt;typename T&amp;gt;
T* allocateObject(bool persistent = false) {
    return reinterpret_cast&amp;lt;T*&amp;gt;(allocate(sizeof(T), persistent));
}

template&amp;lt;typename T&amp;gt;
void deallocateObject(T*&amp;amp; obj) {
    deallocate(obj, sizeof(T));
    obj = nullptr;
}

// ----------------------
// C-style allocation
// ----------------------
void* mallocAlloc(size_t size, bool persistent = false) {
    void* ptr = std::malloc(size);
    if (!ptr) throw std::bad_alloc();
    registerAllocation(ptr, persistent);
    return ptr;
}

void freeAlloc(void*&amp;amp; ptr, size_t size) {
    if (!ptr) return;
    unregisterAllocation(ptr);
    std::free(ptr);
    ptr = nullptr;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;private:&lt;br&gt;
    Arena&amp;amp; getOrCreateArena(size_t size) {&lt;br&gt;
        thread_local static std::unordered_map&amp;gt; localMap;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if (localMap.find(size) != localMap.end())
        return *localMap[size];

    std::shared_ptr&amp;lt;Arena&amp;gt; arena;
    {
        std::shared_lock&amp;lt;std::shared_mutex&amp;gt; lock(allocMutex);
        if (globalArenas.find(size) != globalArenas.end())
            arena = globalArenas[size];
    }
    if (!arena) {
        std::unique_lock&amp;lt;std::shared_mutex&amp;gt; lock(allocMutex);
        arena = std::make_shared&amp;lt;Arena&amp;gt;();
        arena-&amp;gt;blockSize = size;
        arena-&amp;gt;freeListHead.store(nullptr);
        arena-&amp;gt;totalBlocks = 0;
        globalArenas[size] = arena;
    }

    localMap[size] = arena;
    return *arena;
}

// ----------------------
// Allocation tracking
// ----------------------
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;public:&lt;br&gt;
    void registerAllocation(void* ptr, bool persistent = false) {&lt;br&gt;
        std::unique_lock&lt;a&gt;std::shared_mutex&lt;/a&gt; lock(allocMutex);&lt;br&gt;
        if (allocations.find(ptr) != allocations.end())&lt;br&gt;
            throw std::runtime_error("Double allocation detected");&lt;br&gt;
        allocations.insert(ptr);&lt;br&gt;
        threadLocalAllocations.insert(ptr);&lt;br&gt;
        if (persistent) persistentAllocations.insert(ptr);&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void unregisterAllocation(void* ptr) {
    std::unique_lock&amp;lt;std::shared_mutex&amp;gt; lock(allocMutex);
    auto it = allocations.find(ptr);
    if (it == allocations.end())
        throw std::runtime_error("Double free / invalid free");
    allocations.erase(it);
    threadLocalAllocations.erase(ptr);
    persistentAllocations.erase(ptr);
}

void cleanupThreadLocal() {
    for (auto ptr : threadLocalAllocations) {
        unregisterAllocation(ptr);
        ::operator delete(ptr);
    }
    threadLocalAllocations.clear();
}

// ----------------------
// Bounds checking
// ----------------------
template&amp;lt;typename T&amp;gt;
void checkBounds(T* arr, size_t index, size_t size) {
    if (productionBoundsCheck &amp;amp;&amp;amp; index &amp;gt;= size)
        throw std::out_of_range("Array index out of bounds");
}

// ----------------------
// RAII for OS / External resources
// ----------------------
class FileHandle {
    std::ofstream* file;
    HPMemoryManager&amp;amp; memMgr;
public:
    FileHandle(HPMemoryManager&amp;amp; mgr, const std::string&amp;amp; filename) : memMgr(mgr) {
        file = new std::ofstream(filename, std::ios::out);
        if (!file-&amp;gt;is_open()) throw std::runtime_error("Failed to open file");
        memMgr.registerAllocation(file, true);
    }
    std::ofstream&amp;amp; get() { return *file; }
    ~FileHandle() {
        if (file &amp;amp;&amp;amp; file-&amp;gt;is_open()) file-&amp;gt;close();
        memMgr.deallocateObject(file);
    }
};

// ----------------------
// Async task execution
// ----------------------
template&amp;lt;typename F&amp;gt;
void runAsync(F&amp;amp;&amp;amp; func) {
    std::thread([this, func]() {
        func();
        cleanupThreadLocal();
    }).detach();
}

// ----------------------
// Destructor
// ----------------------
~HPMemoryManager() {
    std::unique_lock&amp;lt;std::shared_mutex&amp;gt; lock(allocMutex);
    if (!allocations.empty()) {
        std::cerr &amp;lt;&amp;lt; "Memory leaks detected: " &amp;lt;&amp;lt; allocations.size() &amp;lt;&amp;lt; "\n";
        for (auto ptr : allocations) ::operator delete(ptr);
    }
    for (auto&amp;amp; [size, arena] : globalArenas) {
        ArenaBlock* block = arena-&amp;gt;freeListHead.load();
        while (block) {
            ArenaBlock* next = block-&amp;gt;next.load();
            ::operator delete(block);
            block = next;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;};&lt;/p&gt;

&lt;p&gt;// ----------------------&lt;br&gt;
// SharedObject for multi-level DAG / cyclic cleanup&lt;br&gt;
// ----------------------&lt;br&gt;
class SharedObject {&lt;br&gt;
private:&lt;br&gt;
    std::weak_ptr weakSelf;&lt;br&gt;
    std::vector&lt;a&gt;std::shared_ptr&amp;lt;SharedObject&lt;/a&gt;&amp;gt; children;&lt;/p&gt;

&lt;p&gt;public:&lt;br&gt;
    void setSelf(std::shared_ptr self) { weakSelf = self; }&lt;br&gt;
    void addChild(std::shared_ptr child) { children.push_back(child); }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void cleanupGraph(std::unordered_set&amp;lt;SharedObject*&amp;gt;&amp;amp; visited) {
    if (visited.find(this) != visited.end()) return;
    visited.insert(this);
    for (auto&amp;amp; child : children) {
        if (child) child-&amp;gt;cleanupGraph(visited);
    }
    children.clear();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;};&lt;/p&gt;

&lt;p&gt;// ----------------------&lt;br&gt;
// Demo / Testing&lt;br&gt;
// ----------------------&lt;br&gt;
int main() {&lt;br&gt;
    HPMemoryManager mem;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {
    // Single object
    int* a = mem.allocateObject&amp;lt;int&amp;gt;();
    *a = 42;
    std::cout &amp;lt;&amp;lt; "Single object: " &amp;lt;&amp;lt; *a &amp;lt;&amp;lt; "\n";
    mem.deallocateObject(a);

    // Array allocation
    int* arr = reinterpret_cast&amp;lt;int*&amp;gt;(mem.allocate(sizeof(int) * 10));
    for (int i = 0; i &amp;lt; 10; i++) {
        mem.checkBounds(arr, i, 10);
        arr[i] = i * 5;
    }
    for (int i = 0; i &amp;lt; 10; i++) std::cout &amp;lt;&amp;lt; arr[i] &amp;lt;&amp;lt; " ";
    std::cout &amp;lt;&amp;lt; "\n";
    mem.deallocate(arr, sizeof(int) * 10);

    // Persistent memory
    int* persistentInt = mem.allocateObject&amp;lt;int&amp;gt;(true);
    *persistentInt = 999;
    std::cout &amp;lt;&amp;lt; "Persistent value: " &amp;lt;&amp;lt; *persistentInt &amp;lt;&amp;lt; "\n";

    // Async tasks
    mem.runAsync([&amp;amp;mem]() {
        int* tdata = mem.allocateObject&amp;lt;int&amp;gt;();
        *tdata = 777;
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        mem.deallocateObject(tdata);
    });
    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    // RAII file demo
    {
        HPMemoryManager::FileHandle fh(mem, "highperf_safe.txt");
        fh.get() &amp;lt;&amp;lt; "High-performance enterprise memory manager demo\n";
    }

    // DAG / cyclic references
    std::shared_ptr&amp;lt;SharedObject&amp;gt; parent = std::make_shared&amp;lt;SharedObject&amp;gt;();
    parent-&amp;gt;setSelf(parent);
    std::shared_ptr&amp;lt;SharedObject&amp;gt; child = std::make_shared&amp;lt;SharedObject&amp;gt;();
    parent-&amp;gt;addChild(child);
    std::unordered_set&amp;lt;SharedObject*&amp;gt; visited;
    parent-&amp;gt;cleanupGraph(visited);

} catch (const std::exception&amp;amp; e) {
    std::cerr &amp;lt;&amp;lt; "Error: " &amp;lt;&amp;lt; e.what() &amp;lt;&amp;lt; "\n";
}

return 0; // Destructor auto-cleans everything
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>cpp</category>
      <category>computerscience</category>
      <category>performance</category>
    </item>
  </channel>
</rss>
