CS50 problem set 2 作業回顧

陳雁智 (Marat Y. C. Chen)
Manjeaneer
Published in
4 min readOct 17, 2017

--

起初看到 ptt 有人徵 cs50 讀書會起了好奇心,又逛到 Huli 的介紹文,就進 edX 報名了這堂課,大學時自學過兩週的 Matlab 跟一點 C++加上資料結構,對整體的認識實在不夠完整,趁這次再一次認識一下電腦科學 (Computer Science) 這門學問建立起連結零碎知識片段。

課程內容在 google 上己經有查不完的內容了,這次選擇寫2017的作業 (problem sets) 卡住的一些雷

pset 2 crypt

作業已經提示要使用 crypt 這個函式,但此時還沒有指標觀念,一開始想把 crypt 產生出 hashed 值這段用函式包起來傳出 CS50 函式庫定義的 string,如以下的 pseudo code:

for key in [a..ZZZZ]
hashed_to_be_tested = generated_hashed(key)
string generated_hashed(key):
return crypt(key, salt)

若整支程式只用一次 crypt 倒沒問題,若在其它區塊再次用了 crypt 產生值,則可能產生額外行為而不符合原先設想的邏輯,一直到除錯時才發現變數值不合預期而注意變數的指標沒變才發現 crypt 的行為: crypt 回傳的指標 (char*) 都是固定的

對指標稍熟後再次驗證確實沒錯,如以下程式

#define _XOPEN_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
// initilize two pointers with the returned values from crypt
char* hashed_1 = crypt("abc", "50");
char* hashed_2 = crypt("def", "50");
// initailize two new pointers with memory allocation
char* hashed_3 = NULL;
hashed_3 = malloc(sizeof(char)*14);
strcpy(hashed_3,crypt("abc", "50"));
char* hashed_4 = NULL;
hashed_4 = malloc(sizeof(char)*14);
strcpy(hashed_4,crypt("def", "50"));

printf("1st key: %p, value: %s\n", hashed_1, hashed_1);
printf("2nd key: %p, value: %s\n", hashed_2, hashed_2);
printf("3rd key: %p, value: %s\n", hashed_3, hashed_3);
printf("4th key: %p, value: %s\n", hashed_4, hashed_4);

}
// clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wshadow crypt.c -lcrypt -lm -o crypt

結果:第一跟第二個變數被賦給了相同的指標值而印出時產生一樣的結果,而第三跟第四個變數在先配置記憶體後得到的指標值剛好差了 0x20: 也就是32bytes,這裡發現有趣的東西,研究一下再來分享

1st key: 0x7fbc8dcc21c0, value: 501slZ9s3gdss
2nd key: 0x7fbc8dcc21c0, value: 501slZ9s3gdss
3rd key: 0x22a7420, value: 50PaJ4.RO0YUo
4th key: 0x22a7440, value: 501slZ9s3gdss

下回寫遞迴實作二分搜尋時自己犯的新手錯誤,過程中不斷體會 ptt 程設版常看到的簽名檔,實在沒錯

“遞迴只應天上有,凡人該當用迴圈”

“To iterate is human, to recurse, divine”

--

--

陳雁智 (Marat Y. C. Chen)
Manjeaneer

project manager/savvy programmer/marathon runner/critical reader