Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C++

Heap Manager for Allocating Memory from a Shared Memory Segment

Rate me:
Please Sign up or sign in to vote.
4.73/5 (13 votes)
20 Jun 2006CPOL9 min read 87.8K   1.8K   48  
A heap manager for allocating memory from a shared memory segment.
/**
 * Virtual and shared memory manager classes (Windows implementation)
 *
 * This source code is free and anyone can copy, pirate or distribute
 * the code without prior written or vocal permission.
 *
 * This software is provided "AS IS" and without any express or implied
 * warranties, including, but not limited to, the implied warranties of
 * merchantability and fitness for a particular purpose are disclaimed.
 *
 * Written By: Pradeep Chulliyan (chulliyan@hotmail.com)
 * Dated: June 07 2006
 */
#include "shmmgr.h"

/////////////////////////// CVirtualMemory ///////////////////////////////
//
// Allocate memory using 'VirtualAlloc' API
//
bool CVirtualMemory :: Alloc (int pages)
{
    DWORD flg = m_reserve ? MEM_RESERVE : MEM_COMMIT;
    if (pages <= 0)
        pages = 1;

    this->m_len = pages * GetPageSize();
    this->m_ptr = (BYTE*)::VirtualAlloc (0, this->m_len, flg, PAGE_READWRITE);

    SetMaximumSize();

    return (this->m_ptr != 0);
}

// Free allocated memory
//
void CVirtualMemory :: Free()
{
    if (m_local == true && m_max)
    {
        ::VirtualFree (this->m_ptr, this->m_len, MEM_DECOMMIT);
        ::VirtualFree (this->m_ptr, 0, MEM_RELEASE);
    }
    this->m_ptr = 0;
    this->m_len = 0;
    this->m_max = 0;
}

// Commit a region of memory. If the memory is not in RESERVED
// but not COMMITTED mode return immediately.
//
bool CVirtualMemory :: Commit (void* ptr, int len)
{
    if (m_reserve == false || !m_max)
        return true;

    // Set minimum commit size
    //
    len = (int)GetCommitSize ((DWORD)len);

    // Determine the upper boundary
    //
    BYTE* m = ((BYTE*)ptr) + (len - 1);
    if (m >= &this->m_ptr[this->m_len])
        m = &this->m_ptr[this->m_len - 1];

    // Check if the memory has been committed or not
    //
    if (m >= m_max)
    {
        MEMORY_BASIC_INFORMATION mi = {0};
        if (::VirtualQuery (m, &mi, sizeof (MEMORY_BASIC_INFORMATION)))
        {
            if ((mi.State & MEM_COMMIT) > 0)
                return true;
        }

        DWORD a = GetPageSize() - 1;
        DWORD l = (DWORD)((m - m_max) + a) & ~(a);

        l = GetCommitSize (l);
        l = (l + a) & ~(a);

        m_max  = (BYTE*)::VirtualAlloc (m_max, l, MEM_COMMIT, PAGE_READWRITE);
        m_max += l;
    }
    return true;
}

///////////////////////////// CSharedMemory //////////////////////////////
//
// Create a shared memory segment
//
bool CSharedMemory :: Alloc (LPCTSTR name)
{
    DWORD dw = PAGE_READWRITE;
    if (m_reserve)
        dw |= SEC_RESERVE;

    // Create file mapping object
    //
    ::SetLastError (0);

    m_mem = ::CreateFileMapping (INVALID_HANDLE_VALUE, 0, dw, 0, this->m_len, name);

    // Check if this is the first instance
    //
    if (::GetLastError() != ERROR_ALREADY_EXISTS)
        m_first = true;

    if (m_mem.IsValid())
    {
        this->m_ptr = (BYTE*)::MapViewOfFile (m_mem, FILE_MAP_READ|FILE_MAP_WRITE,
                                              0, 0, this->m_len);
    }
    return (this->m_ptr != 0);
}

// Free shared memory segement
//
void CSharedMemory :: Free()
{
    if (this->m_ptr)
    {
        ::UnmapViewOfFile (this->m_ptr);
        m_mem.Close();

        CVirtualMemory::Free();
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I have been writing code for a living for last three hundred years! I have written code in almost all the languages- C/C++, JAVA, C#, VB, Pascal, Delphi, JScript and so on.

Comments and Discussions