How can I create my own memory manager to manage this continuous piece of memory without the help of other memory managers (such as Malloc / New) in C ++?
Here is another context:
MemManager::MemManager(void* memory, unsigned char totalsize) { Memory = memory; MemSize = totalsize; }
I need to be able to allocate and free blocks of this contiguous memory using MemManager. The constructor gets the total size of the chunk in bytes.
The Allocate function should take the amount of memory needed in bytes and return a pointer to the beginning of this memory block. If there is no memory left, a NULL pointer is returned.
The Deallocate function must take a pointer to a block of memory to be freed and return it to MemManager for future use.
Please note the following restrictions:
- In addition to the memory provided to him, MemManager cannot use ANY dynamic memory
- As originally stated, MemManager CANNOT use other memory managers to perform its functions, including the new / malloc and delete / free
I already got this question at several interviews, but even hours of research on the Internet did not help me, and I failed every time. I found similar implementations, but they all either used malloc / new, or were intended for general purpose and requested memory from the OS, which I am not allowed to do.
Please note that it is convenient for me to use malloc / new and free / delete and work with them with minor problems.
I tried implementations that use node objects in the LinkedList method, which point to a allocated block of memory and determine how many bytes were used. However, with these implementations, I always had to create new nodes on the stack and insert them into the list, but as soon as they went out of scope, the whole program broke down, because addresses and memory sizes were lost.
If anyone has an idea on how to implement something like this, I would really appreciate it. Thanks in advance!
EDIT: I forgot to explicitly indicate this in my original post, but the objects selected by this MemManager can be of different sizes.
EDIT 2: I ended up using homogeneous memory blocks, which was actually very easy to implement thanks to the information provided below. Exact rules regarding the implementation itself were not specified, so I divided each block into 8 bytes. If the user requested more than 8 bytes, I would not be able to provide it, but if the user requested less than 8 bytes (but> 0), I would give additional memory. If the amount of memory transferred inside is not divisible by 8, then in the end memory will be lost, which, I believe, is much better than using more memory than you.