Try   HackMD

2023q1 Homework6 (quiz5)

contributed by < chiacyu >

測驗 1

pool_init 的過程中,需要透過一個 meta data 的資料結構來記錄這個 block 裡面的資訊,因此若是 size 小於 header_size 就會返回失敗。

bool pool_init(void *addr, int size)
{
    if (!addr) /* not a valid memory address */
        return false;

    if (size <= header_size) /* size is too small, can notstore a header */
        return false;

    tmp_block = 0;
    tmp_pt = 0;

    pool_size = size - word_size;
    pool_free_space = size - word_size;

    current = (block_t *) addr;
    current->size = pool_free_space;
    current->prev = NULL, current->next = NULL;

    return true;
}

round_up 程式將size 取至 32bit or 64bit 的倍數。 在 enum 裡面可以看到,若 __SIZE_WIDTH__ 在前置處理器時有被定義成 64log2_word_size = 3,此外則為 log2_word_size = 2

enum {
    word_size = __SIZE_WIDTH__ / 8, /**< size of memory element */
#if __SIZE_WIDTH__ == 64
    log2_word_size = 3,
#else
    log2_word_size = 2,
#endif
    header_size = 3 * word_size, /**< size, previous/next block addresses */
};
static inline int round_up(const int *x)
{
    return ((*x + 7) >> word_size) << word_size;
}

再來可以看到 pool_malloc() 來看看如何配置記憶體空間。首先透過 int _size = round_up(&size); 來取下一個 64bit32bit 的倍數。

再來要檢查如果如果 pool 中的剩餘空間,透過 pool_free_space 來紀錄。 若是 pool_free_space 小於 header_size 則要馬上回傳 NULL

if (pool_free_space <= (_size + header_size)) {
        return NULL;
}

再來如果確認空間足夠,再來就是找到適合的 block

void *ret = get_loc_to_place(current, _size);

若是執行成功後 ret 則為分配的 block 地址。