1
考慮以下 C 程式,預期輸出結果為何?
假定 Q1 為 puts
輸出的內容,那應該為何?
作答區
Q1 = ?
(a)
one(b)
not oneReference: Bit field
延伸題目:為什麼?舉出 Linux 核心中用到 bit field 的原始程式碼並解說其用途
2
考慮以下程式,留意到 ptr[1][2][3][4]
:
請將 ptr[1][2][3][4]
改寫為功能等價的 A [ B [ C [ D [ ptr ] ] ] ]
,其中 A, B, C, D 都是介於 1 到 4 之間的數值,那麼:
作答區
A = ?
(a)
1(b)
2(c)
3(d)
4B = ?
(a)
1(b)
2(c)
3(d)
4C = ?
(a)
1(b)
2(c)
3(d)
4D = ?
(a)
1(b)
2(c)
3(d)
4延伸題目:這樣的操作可體現在哪?請在 GitHub 找出既有的開放原始碼專案來解說。
提示:某些 libc 的字串處理的程式碼類似以下:
3
考慮到以下 C 程式:
在 LP64 的執行環境中,其輸出的形式為 "K1 K2",那麼:
作答區
K1 = ?
(a)
-1(b)
0(c)
1(d)
4294967295(e)
-2147483648K2 = ?
(a)
-1(b)
0(c)
1(d)
4294967295(e)
-2147483648提示: CS:APP 3/e 第 2 章提過 integer overflow。在 C 規格書裡頭涉及 promotion
延伸題目:在 C99/C11 規格書找出具體原因,並思索對應的安全議題
4
以下程式碼改寫自 Linux 核心原始程式碼,請對照註解 (預期功能),指出實作上的問題,假設輸入 value
不會超過 32-bit。
作答區
Q2 = ?
(a)
第 10 行總是輸出錯誤結果;(b)
第 6 到 8 行的轉型會導致 undefined behavior;(c)
value
不該用 uint32_t
,這會導致轉型過程中的資料遺失;(d)
位移非正值會導致 undefined behavior;延伸題目:
5
考慮以下程式碼,在 x86_64 搭配 glibc 實作,printf
函示的輸出為何?
提示: C99 規格書 6.5.2.3
提到:
If the member used to access the contents of a union object is not the same as the member last used to store > a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type.
作答區
K3 = ?
(a)
-1(b)
0(c)
1(d)
4294967295(e)
-2147483648延伸題目:解釋為何如此
6
考慮到某個 linked list 的資料結構宣告如下:
典型新增節點到 linked list 尾端的程式碼實作如下:
其中 new_node
是已配置的節點記憶體位址。
請比照 你所不知道的C語言: linked list 和非連續記憶體操作 的「有品味」版本,把 if-else 敘述消除,改寫為以下等效的程式碼:
補完欠缺的程式碼 (Z1 和 Z2)
作答區
Z1 = ?
(a)
link = link->next(b)
*link = link->next(c)
link = *(link->next)(d)
link = &(*link)->nextZ2 = ?
(a)
new_node->next = *link(b)
(*new_node)->next = *link(c)
new_node->next = link(d)
*new_node->next = *linkReference:
延伸題目:在 Linux 核心原始程式碼找到類似的程式碼並解說
7
考慮以下透過 Huffman coding 進行資料壓縮的程式碼 (huff.c
):
參考執行結果為:
請嘗試補完上述 build_pairings
函式裡頭透過遞迴呼叫的敘述 XXA
和 XXB
。
作答區
XXA = ?
(a)
build_pairings(root->left, arr, top - 2, pairs);(b)
build_pairings(root->left, arr, top - 1, pairs);(c)
build_pairings(root->left, arr, top, pairs);(d)
build_pairings(root->left, arr, top + 1, pairs);(e)
build_pairings(root->left, arr, top + 2, pairs);XXB = ?
(a)
build_pairings(root->right, arr, top - 2, pairs);(b)
build_pairings(root->right, arr, top - 1, pairs);(c)
build_pairings(root->right, arr, top, pairs);(d)
build_pairings(root->right, arr, top + 1, pairs);(e)
build_pairings(root->right, arr, top + 2, pairs);延伸題目: