jollen.org

Jollen 的 Blog
Jollen's email: jollen # jollen.org
more:  Jollen's Training

.bss section 的觀念:uninitialized data section

.作者:jollen/
.日期:December 15, 2006 1:11 AM


.bss 節區存放「uninitialized data」,由程式碼的角度來看,就是「未初始化的變數」。我們直接以一段 code 來說明,讓大家更清楚這樣的概念。

#include <stdio.h>

int foo; int bar;
int main(void) { int *ptr;
printf(".bss section starts at %08p\n", &foo);
printf("foo is %d.\n", foo);
ptr = &foo; *ptr = 12345;
printf("foo is %d.\n", foo); printf(".bss section starts at %08p\n", &foo);
return 0; }

這段 code 相當簡單,但是隱含幾個重要的觀念,條列說明如下:

1. foo 是一個變數,在程式碼裡沒有被初始化(uninitialized),所以程式執行時(process),foo 變數會被擺在「.bss section」。
2. 同理,bar 變數也是。
3. foo 是第一個 uninitialized data,所以他的 virtual address,形同 .bss section 的開始位址(process virtual address)。

程式要實驗的項目如下:

1. 觀念 3. 的應用,我們印出 .bss section 的 start address。
2. foo 是全域變數,未初始化時的值是 0(zero)。
3. 用 '*ptr' 指向 .bss section 的 start address,此位址等於 foo 變數的值。
4. 把 .bss section 啟始位址處記憶體的值(value)改成 12345(透ptr 指標)。

沒搞錯的話,foo 變數的值就會變成 12345。

以下是執行結果:

# ./bss
.bss section starts at 0x8049588
foo is 0.
foo is 12345.
.bss section starts at 0x8049588

很特別的一個 section,值得深入研究。

Tags:

純手工打造說明:技術專欄文章為 Jollen 原創,內容皆為人工撰寫,無 AI 生成。轉載請註明出處與作者,並全文引用。轉載時請在文章開頭或結尾明顯處註明「本文出處:https://www.jollen.org,已取得原作者同意並授權使用。」
訂閱電子報:不定期 Jollen's Blog 精選文章隨 Moko365 電子報寄送;請透過 Moko365 電子報訂閱(可隨時取消)。

Copyright(c) 2001–2006 www.jollen.org. All rights reserved.
Last update: 2026-07-22