2011-03-13 108 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