Ch16 Segmentation
這一章(第16章)是在講作業系統中記憶體管理的一種方式:Segmentation(段式管理)。
以下是整章的重點與概念講解:
背景
傳統上來說,我們會把整個 virtual address space 搬到 physical address 中。產生以下問題:
- Virtual address space 中間有很多空白區域,會造成 internal fregmentation
- 如果 address space 很大,但實際用到很少,搬運的效率會很差
Intro
Segmentation 是把一個程式的 virtual address space 切成邏輯上獨立的區段(segments),例如:
- Code segment
- Heap segment
- Stack segment
每個 segment 都會有自己的 base 和 bounds registers,這樣可以分開搬移,省記憶體,也更有彈性。
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
Address translation
- 根據高位元來判斷是哪個 segment
- 取出 offset,加上該 segment 的 base,轉換成 physical address
- 並檢查 offset 有沒有超過 segment 大小
- 如果超過會回傳 segmentation fault
因為 Stack 的堆疊方向跟其他 segment 不一樣(向下成長),必須做特別處理
範例:

Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
Protection
Segment 也有保護權限:
- Code:Read + Execute
- Heap/Stack:Read + Write
因為 code 只有 read 與 execute 的權限,因此不用怕被別人改到程式碼,多個 process 可以共用一個 code
External Fragmentation
因為 segment 大小不一,會導致實體記憶體中出現許多小碎塊,稱為外部碎裂(external fragmentation)。這會讓:
- 新的 segment 找不到連續空間
- segment 想成長但被擋住
解法如下:
- Compaction(壓縮):重新整理記憶體,把 segments 移動合併,但代價高
- Free-list 管理演算法:如 best-fit、first-fit、buddy system 等