Pset5 - tips

In speller.c, we’ve put together a program that’s designed to spell-check a file after loading a dictionary of words from disk into memory.

"free関数を使い忘れてもプログラム終了時には自動的に解放されますが、その間不必要にメモリを占有していることになるわけですから、用が済んだら速やかにfreeで解放するのが原則です。"

  • c言語でstring (char array)を作る時、最後に\0は入れましょう。
  • 種々の関数やhash table等、定義に関してはmainから外れていい。だが、実行して欲しい時はmainに入れ、自分で呼ぶべし。

構造体の宣言では、箱の形を決めているだけなので、構造体の中で値は指定できない。

typedef struct node
{
    char word[LENGTH + 1];
    struct node* next = NULL;
}
node;

とか、だめで、

typedef struct node
{
    char word[LENGTH + 1];
    struct node* next;
}
node;

と言ってから
node* new_node;
new_node->next = NULL;
が正しい。う〜ん、面倒...

  • valgrind とmakeとで実行結果が違うの...メモリまわりがバグってるとよくあるのね(唖然)

f:id:owan_k:20160917225420p:plain
f:id:owan_k:20160917225429p:plain
For counts of detected and suppressed errors, rerun with: -vは、
valgrind -v speller ...と実行すれば良い。以下も参考にしつつ。
Valgrindの結果の見方、日本語訳、など役に立つことまとめ - 結果だけでなく過程も見てください
色々調べていると...おんなじエラーのひとをみつけた!
cs50.stackexchange.com
修正後:
f:id:owan_k:20160917225919p:plain
lower word最後の'\0'を忘れていたのでした。元々のstringを完コピするなら最後も勝手に0が入るんでない?と考えていたものの、冷静になってみると<の場合ゼロだけコピーされないね。

for (int k = 0; k <= strlen(word); k++) {
       lowerword[k] = tolower(word[k]);
   }

にしてもよかったかな。
ちなみに、結局cs50.stackexchange.comに影響されて書き換えたけれど、LENGTH使う必要もなかったかな。strlen(word) + 1でも事足りたと思われる。