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

标签 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 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_location

            mem_location = cur_location;

之后,在返回其值之前,您可以更改它

    mem_location = mem_location + sizeof(struct memBlock);

好像不太对劲……

关于c - 使用数据结构来处理内存的个人 malloc 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5293315/

相关文章:

c - 先进先出流水线服务器仅接收一定数量的数据

c - 奇怪的 gcc 警告行为

c++ - 有没有一种简单的方法可以在 C++ 中创建最小堆?

javascript - 改进 Javascript 中的数组转换

c - 从函数返回结构

c - 即使满足条件,while 循环也不会中断

c - 在 vtbl 中命名函数指针

c++ - 无法返回头文件中声明的结构 vector

在函数内的堆栈上创建一个结构体,并将其分配给在另一个函数中创建的数组的数组位置

C++ 错误此声明没有存储类或类型说明符