Home > database >  What memory/data structure should I use to divide the memory into blocks/chunks and its implementati
What memory/data structure should I use to divide the memory into blocks/chunks and its implementati

Time:12-22

(THE ALLOCATED DATA CAN BE OF ANY TYPE - int, char, etc..)

I am given a sheet size of 1024 bytes and a maximum of 5 sheets. I need to make some sort of dynamically allocated structure (or structures) that will keep all of the data in one place and divide it into blocks. So I basically need to allocate 1024 bytes (or maybe all of the space I have, 1024x5 bytes) in a structure and use the given memory in blocks differently. And if the sheet runs out of memory I need to allocate a new one.

So my question is: What would be the best structure in c for this job? I was thinking either a vector of char* or void* or maybe a classic c array of char* or void*, but not quite too sure. If it is an array I was wondering maybe I make an array[5] and allocate just the first element and the first element would be a pointer to 1024 bytes of memory?

Here are the functions that will be done with the structure (its a simple implementation of a garbage collector):

1.Allocate block of memory of a given size and return a pointer to that memory

2.Free a block of memory given a "void *region" attribute

3.Increase size of block with given "void *region" and size to increase to

4.Decrease size of block with given "void *region" and size to decrease to

  1. Write information for the allocated blocks of memory in a file

Note: All of the functions are in a class garbage collector and all of them are static of type void (except for the first one, which is of type void*, because it returns a pointer to the newly allocated block)

Note 2: The pages aren't allocated one after another in the machine's memory, so they have different adresses, they're only allocated when they're needed (when space is running out)

CodePudding user response:

I would start out with something like this :

#include <array>
#include <memory>
#include <iostream>

template<std::size_t N>
struct heap_t
{
public:

    // todo add your memory managment 
    // using templates like 

    template<typename type_t>
    type_t* allocate()
    {
        // use sizeof(type_t) etc...
        return nullptr;
    }

    template<typename type_t>
    void free(type_t* ptr)
    {
        // more logic here.
    }

private:
    std::array<char, N> m_memory{0}; // initialize all memory to 0
};

int main()
{
    constexpr std::size_t heap_size{ 256ul };

    // to avoid allocating heap on the stack use make_unique
    auto heap = std::make_unique<heap_t<heap_size>>();
    
    auto value_ptr = heap->allocate<int>();
    
    return 0;
}
  • Related