使用数据结构处理内存的个人malloc函数

使用数据结构处理内存的个人malloc函数,c,data-structures,struct,malloc,allocation,C,Data Structures,Struct,Malloc,Allocation,我有这个函数,只有当它可用并且请求的字节数的大小适合我的小型托管内存时,它才会接收要分配和发回的字节数。 我的问题: 没有分配适当的数据结构,我恐怕无法返回正确的地址。有人知道我如何在另一个程序中将此函数用作库来测试它吗 数据结构 typedef struct memBlock{ struct memBlock* next; unsigned long size; // Size of this block unsigned int is_used; // bool 0 = not used

我有这个函数,只有当它可用并且请求的字节数的大小适合我的小型托管内存时,它才会接收要分配和发回的字节数。 我的问题:

没有分配适当的数据结构,我恐怕无法返回正确的地址。有人知道我如何在另一个程序中将此函数用作库来测试它吗

数据结构

typedef struct memBlock{
struct memBlock* next;
unsigned long size;  // Size of this block
unsigned int is_used;  // bool 0 = not used 1 = used
} memBlock;
MALLOC函数:

char *mm_alloc(unsigned long no_of_chars){

if (!has_initialized) {
    printf("No Memory has been intialized, PLEASE INITIALIZE THE MEMORY BEFORE calling This function\n");
    exit(1);
}


void *cur_location; // this is where we are currentl in our memory pool

memBlock *current_loc_mb; // the current mem block location

char *mem_location; // mem location we will return to the user

/* We are going to have to include the size of our data struct when we are searching for open memory*/
no_of_chars = no_of_chars + sizeof(struct memBlock);

mem_location = 0; // set to 0 until a proper size has been found

cur_location = managed_memory_start; // start at the beginning of our allocated memory

// go until there is no more memory left, allocate until we get to the end of our managed memory
while (managed_memory_start != NULL) {

    /*cur_location and cur_loc_mcb are at the same address initially,
but we use the current location as a pointer to move around our managed memory*/

    cur_loc_mcb = (memBlock *)cur_location; 

    // if our current location is not used
        if (!cur_loc_mcb->is_used) {

            if (cur_loc_mcb->size >= no_of_chars) {

                // we have found a size big enough or equal to what the user asks for
                cur_loc_mcb->is_used = 1; 
                mem_location = cur_location; 

                break;

            }
        }

// at this point we dont have a size big enough, move to the next one
cur_location = cur_location + cur_loc_mcb->size; 

}
/*Move the memory past or MCB and return*/

mem_location = mem_location + sizeof(struct memBlock);

return mem_location;
}

您可以在代码的某个地方设置mem_位置

            mem_location = cur_location;
稍后,在返回其值之前,您会更改它

    mem_location = mem_location + sizeof(struct memBlock);

这似乎不对…

“有人知道我如何在另一个程序中将此函数用作库来测试它吗?”这意味着您也有另一个程序的测试套件。否则,你怎么知道你得到了他们的功能的良好覆盖,因此你的功能?一个更好的方法可能是为您自己的malloc库进行自动化测试,因为这样您就可以保证角落案例的覆盖率。如果您已经有了这个,那么您在这个问题中所问的可能是一个很好的第二步。您是以
C
的身份编译的吗?强制转换(
cur_loc_mcb=(memBlock*)cur_location;
)是虚假的,应该由编译器来执行。@Merlyn Morgan Graham,我正在寻找一些关于我目前正在编写的这些功能的测试用例想法。无法判断您是否要求的内存超过最大块中的可用内存。如果您这样做,您将永远不会离开while循环(直到程序出现segfaults,也就是说),因此while(mem_start!=null)将永远运行,即使我仔细检查了整个块。否则,我如何遍历我的内存块,直到我一块也没有剩下。看起来他将分配元数据与可用内存内联,直接位于每个分配块和空闲块之前。他使用
cur_location=cur_location+cur_loc_mcb->size逐步遍历元数据条目