User-implemented memory management [closed]

左心房为你撑大大i 提交于 2020-01-16 09:29:14

问题


I am given a C project assignment in which I am asked to implement a simple memory management library. The way it works is that it has init function which takes a pointer(void*) to a chunk of memory allocated by another c program along with the size of the chunk and has two other functions to allocate a block of requested size from the said chunk and deallocate a block when passed back the pointer pointing to it.

Problem is that I am asked to keep my management structures inside the chunk itself and I have zero idea on how to do that. I thought about dividing the chunk into frames but how can I keep track of which frames are allocated without using anything from outside the chunk?

Edit: Init function is used like this. There is this program which will call the library I am going to write. It will allocate a chunk of memory using either malloc or calloc. Then it will call the init function from the library and pass the pointer to that memory chunk along with the size of the chunk to it.

What my library will do with that chunk is to allocate blocks from it on demand. So my library's allocate function actually is a call to request a block of memory(size is passed as an argument) from the chunk. And it will return a (void *) pointer pointing to the allocated memory block.

Edit2: To make the situation more clear, my library has to be able to allocate and deallocate which means holes will appear in the chunk it is managing and it will employ either first-fit, best-fit or worst-fit.

Edit3: Is there a way to convert memory addresses into long int?


回答1:


Here's a rough idea of what you would need to do:

The memory segment should be structured as a linked list of blocks. Each block starts with a copy of your management structure followed by the memory that you allocate.

On initialization, point the head of the linked list to the start of the given memory segment. Set the size to the size of the segment minus the size of the management structure, and set the next pointer to NULL.

When the first allocation request is made, set the size of the head block to the requested size, then set the next pointer to the memory immediately after that. Set the size of the new block to the old head size minus the requested size and the size of the management struct.

For a deallocation, you would need to find the block prior to the one you're about to release. Change the size of the prior block to the size of the freed block plus the struct size, then change the next pointer to the freed block's next pointer.

That should be enough to get you started.



来源:https://stackoverflow.com/questions/59291857/user-implemented-memory-management

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!