2011-03-13 110 views
0

我有这个函数,将采取一定数量的字节分配和发回只有当它是可用的,并请求的字节数的大小适合我的小托管记忆。 我的问题:个人malloc函数,使用数据结构来处理内存

适当的数据结构没有被分配,我恐怕我不会找回正确的地址。有谁知道我可以如何使用它作为另一个程序中的库来测试这个函数?

数据结构

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; 
} 
+0

“有谁知道我可以用它在另一个程序库测试这个功能吗?”这意味着你还有另一个程序的测试套件。否则,你怎么知道你获得了*他们的*功能的好覆盖,因此*你的*功能?要做的更好的事情可能是对自己的malloc库进行自动化测试,因为那样可以保证角落案例的覆盖。如果你已经有了这个,那么你在这个问题上问的问题可能是第二步。 – 2011-03-14 00:02:55

+1

你正在编译为'C'吗?转换('cur_loc_mcb =(memBlock *)cur_location;')是虚假的,应该留给编译器去做。 – pmg 2011-03-14 00:36:44

+0

@ Merlyn Morgan-Graham,我正在寻找一些测试案例的想法,以我目前正在撰写的这些功能。 – Warz 2011-03-14 03:27:37

回答

0

某处在你的代码中设置mem_location

  mem_location = cur_location; 

,后来,就在返回前的v ALUE,你改变它

mem_location = mem_location + sizeof(struct memBlock); 

它看起来不正确...

+0

看起来他有分配元数据与可用内存内联,直接在每个分配的块和空闲块之前。他用'cur_location = cur_location + cur_loc_mcb-> size;'遍历元数据条目,直到他找到足够大的空闲空间。然后他只是通过元数据来获取指向程序员可以写入的空闲空间的指针。但是,没有理由改变它两次。 – 2011-03-14 01:15:55

+0

我正在做Null Set正在谈论的内容。 mem_location = mem_location只是在我将用户送回分配的空间之前将它对齐 – Warz 2011-03-14 03:26:18