contributed by < brianlin314
>
首先,先了解 Memory pool 的概念,可以得知它是一個有效率的方法,預先規劃一定數量的記憶體區塊,使得整個程式可以在執行期規劃 (allocate)、使用 (access)、歸還 (free) 記憶體區塊。
看到 jserv/mpool.c 中的 mpool.h
,閱讀註解,並理解每個 function 的作用。
其中看到 calloc()=malloc()+erase(),並重新探討了一下 malloc 與 calloc 的差異,得知 malloc 與 calloc 不同的是,malloc 在分配內存空間時不會將其初始化為零,而是返回一個指向未初始化內存塊的指針。使用 malloc 時需要注意,由於其不會對內存空間進行初始化,可能會導致程序出現未定義行為的情況。
再來了解到 allocated block 和 free block 內所存放的東西,其中 free block 存儲了下一個和上一個 free block 的位址,因此,malloc() 和 free() 可以使用這些鏈接來解析池,分配一個 chunk 或釋放 chunk。
Free block In-use block
┌────────────────┐ ┌────────────────┐
│ Size │ │ Size │
├────────────────┤ ├────────────────┤
│ Next Block Ptr │ │ │
├────────────────┤ │ │
│Prev. Block Ptr │ │ Payload │
├────────────────┤ │ │
│ │ │ │
│ ........ │ │ │
│ │ │ │
└────────────────┘ └────────────────┘
pool_init() 是一開始初始化 Memory pool 的 function ,如果正確分配會回傳 True,看到此註解 /* size is too small, can notstore a header */
,可得知 AAAA 應為 header_size,且 header_size 裡面儲存的是 size 和 previous/next block addresses。
接著看到 pool_malloc(),為了滿足硬體對齊,4 bytes for 32 bits architecture, or 8 bytes for 64 bits architecture
,所以寫了一個 round_up(),因此 BBBB 與 CCCC 應填上 log2_word_size。
如果 pool_free_space 小於 _size + DDDD,則回傳 NULL,表示 allocate buffer 失敗,所以 DDDD 應填 header_size。
get_loc_to_place(current, EEEE) 是要尋找一個空的空間存放 block,所以EEEE 應填 _size
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing