简体   繁体   English

内存分配模拟问题

[英]Memory Deallocation Simulation Issue

I am simulating a memory block with a static array of structs that take the form of: 我正在用结构形式的静态数组模拟内存块:

typedef struct memBlock
{
  unsigned int isAllocated = 0;
  unsigned int processID = 0;
}memBlock;

I have already got a malloc() -like function that will simulates malloc by taking in the requested memory size from a process and marking part of the array as occupied by setting the isAllocated equal to 1, and changing the PID to the process ID of the requesting process. 我已经有一个malloc()的函数,该函数将通过从进程获取请求的内存大小并通过将isAllocated设置为1并将PID更改为的进程ID来标记数组的一部分为占用空间,从而模拟malloc。请求过程。

So now I want to write a function like free that will deallocate "memory" from this array by setting isAllocated to 0 and PID to 0, but how should I accomplish this? 因此,现在我想编写一个诸如free的函数,该函数通过将isAllocated设置为0并将PID设置为0来从该数组中取消分配“内存”,但是我应该如何实现呢? I know conceptually that I need to start at index 0 of this array and maybe check for the first index where isAllocated = 1 and a nonzero PID right? 我从概念上知道我需要从该数组的索引0开始,也许检查isAllocated = 1和非零PID的第一个索引,对吗? I already have this implemented so far: 到目前为止,我已经实现了这一点:

void* custom_free(void* ptr, unsigned int size)
{
    unsigned int blockIndex = 0, sizeCount = 0, startIndex = 0;
    if(ptr){ free(ptr); }
}

Edit: Earlier in my code I have a malloc call for the memBlock structure like this: 编辑:在我的代码的前面,我对memBlock结构有一个malloc调用,如下所示:

memBlock *block = (memBlock *)malloc(BLOCK_SIZE);

where BLOCK_SIZE is a preprocessor defined constant 其中BLOCK_SIZE是预处理器定义的常量

A common way to store information about allocated memory blocks by an allocator is to store the information structure in the memory block it allocates. 由分配器存储有关已分配内存块的信息的一种常见方法是将信息结构存储在它分配的内存块中。

So instead of allocating size bytes, you allocate size + sizeof(memBlock) bytes, and use the pointer as a pointer to a memBlock structure and fill in the information you need. 因此,您无需分配size字节,而是分配size + sizeof(memBlock)字节,并使用该指针作为指向memBlock结构的指针,并填写所需的信息。 Then return a pointer to the memory after the memBlock structure (ie something like &((memBlock *) ptr)[1] ). 然后在memBlock结构之后返回指向内存的指针(即&((memBlock *) ptr)[1] ))。

When freeing you subtract the size of a memBlock structure to get the original pointer, which points to the memBlock structure. 释放时,减去memBlock结构的大小即可得到原始指针,该指针指向memBlock结构。

This of course makes a member such as isAllocated pretty much useless. 当然,这使像isAllocated这样的成员几乎没有用。 If you have your own blocks, and only allocate in multiples of those blocks, you need to store information about which blocks was allocated, and the number of blocks as well. 如果您拥有自己的块,并且仅以这些块的倍数进行分配,则需要存储有关分配了哪些块以及块数的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM