Design Review Report: Word Counter with Chained Hashing

1. Overview (English)

This report reviews a C program designed to read an English text file, count the occurrences of each word, and display the results using a hash table with a chained hashing collision resolution strategy. The hash function sums up the ASCII values of characters in a word and takes the modulo 256.

1.1. Summary of Procedures

  1. Open an English text file (tom.txt) using fopen.
  2. Read words from the file.
  3. Dynamically allocate memory for each word using malloc.
  4. Associate word occurrences using a hash table (chained hashing).
  5. The hash function sums all character ASCII codes and applies modulo 256.
  6. Dump the contents of the hash table, showing each word and its count.

2. Design Analysis (English)

2.1. Data Structures

The core data structure is struct Item, representing a node in a linked list (chain) for handling hash collisions. The hashtable is an array of pointers to these Item structs.


struct Item {
    int count;       // Word occurrence count
    char *word;      // Pointer to the word string (dynamically allocated)
    struct Item *next; // Pointer to the next item in the chain
};
struct Item *hashtable[256]; // Global hash table array

Good Point: The use of struct Item for linked list nodes is standard and appropriate for implementing chained hashing. The global hashtable array simplifies access.

2.2. Key Functions

Good Point: The modular design with clearly defined functions for each logical step (hashing, string creation, item creation, searching, dumping) is excellent for beginners. It promotes code readability and maintainability.

2.3. Memory Management

malloc is used in create_string and create_item to allocate memory for words and Item structs, respectively. This is correct for storing dynamic data.

Review Point (Memory Leak): The current implementation does not include free() calls for the dynamically allocated memory (both word strings and Item structs) when the program exits. This leads to memory leaks. While acceptable for small demo programs, it's a critical aspect for embedded systems where resources are limited and long-running processes can exhaust memory. For robust code, a cleanup function should iterate through the hash table and free all allocated memory.

2.4. Error Handling

The code includes basic error handling for file opening (fopen) and null pointer checks in `create_string`, `hash`, and `create_item` (though the `hash` check is implicit by loop condition). `search_item` correctly returns `NULL` for not found cases.

Review Point (Input Robustness): The `fscanf(istream, "%99s", buffer)` handles words up to 99 characters. However, if `fscanf` fails to read (e.g., due to EOF or invalid format before 20 iterations), `create_string(buffer)` might be called with an uninitialized or empty `buffer`, which could lead to issues. It's better to check the return value of `fscanf`.


    for (int i = 0; i < 20; i++) {
        if (fscanf(istream, "%99s", buffer) != 1) { // Check if reading was successful
            break; // Exit loop if no more words can be read
        }
        key = create_string(buffer);
        if (key == NULL) { // Handle malloc failure
            perror("Memory allocation failed for key");
            break;
        }
        chainhash(key);
    }
    

Review Point (`create_string` and `create_item` Null Checks): While `create_string` explicitly returns `0` if `buffer` is `0`, and `create_item` returns `0` if `key` is `0`, these `0` returns are not always handled by the caller (`main` and `chainhash`). If `malloc` fails inside these functions, they could return `NULL`, leading to dereferencing `NULL` pointers later. Always check the return value of `malloc`.

2.5. Hash Function

The hash function `total % 256` is simple. For ASCII characters, this works. However, for a general-purpose hash function, it's prone to collisions for words with the same sum of ASCII values (e.g., "ab" and "ba").

Review Point (Hash Function Quality): For more diverse inputs and better distribution, a more sophisticated hash function (e.g., polynomial rolling hash, FNV-1a) would be beneficial. The current sum-based hash function is very simple but will lead to many collisions, especially with common words, potentially degrading performance to O(N) in the worst case for `search_item` and `chainhash` if all words hash to the same bucket.

2.6. Global Variables

The use of global variables `hashtable`, `buffer`, and `key` simplifies parameter passing for beginners. However, in larger projects, it can lead to issues with maintainability and thread safety.

Note (Global Variables): For embedded systems, judicious use of global variables can sometimes be preferred for direct memory access or fixed-size buffers, but it's important to understand the trade-offs regarding scope and potential side effects.

3. Test Results Analysis (English)

The provided test results highlight several critical issues:

4. Recommendations for Embedded Beginners (English)

  1. Implement Memory Cleanup: For embedded systems, memory is a precious resource. Always pair `malloc` with `free`. Implement a function (e.g., `free_hashtable()`) that iterates through all chains and frees each `Item` struct and its `word` string.
  2. Robust Input Reading: Modify the main loop to handle `fscanf` return values to gracefully exit when EOF is reached, rather than hardcoding 20 iterations.
  3. Validate `malloc` Returns: Always check if `malloc` returns `NULL`. If it does, handle the error (e.g., print a message and exit).
  4. Character Encoding: If processing non-ASCII text (like Japanese), you must use wide character functions (`wchar_t`, `wprintf`, `wcslen`, `wcscpy`, `wcscmp`) and adjust the hash function accordingly. Or, if sticking to UTF-8, you'd need a UTF-8 aware parsing library. For simple word counting, sticking to ASCII English is best initially.
  5. Improve Hash Function: While the current hash function works conceptually, consider more robust hash functions for better performance and distribution in real-world scenarios.
  6. Constants for Array Sizes: Use ` #define HASH_MAX 256` instead of hardcoding `256` repeatedly. This makes the code more maintainable.
  7. Variable Scope: Consider declaring `buffer` and `key` locally within `main` to reduce the use of global variables, promoting better encapsulation.

設計レビューレポート: チェイン式ハッシュ法による単語カウンタ

1. 概要 (日本語)

このレポートは、英文テキストファイルを読み込み、各単語の出現回数をカウントし、チェイン式ハッシュ衝突解決戦略を持つハッシュテーブルを使用して結果を表示するCプログラムのレビューを行います。ハッシュ関数は、単語内の文字のASCII値を合計し、256の剰余を取る方法を使用しています。

1.1. 手順の概要

  1. 英文テキストファイル (tom.txt) を fopen で開く。
  2. ファイルから単語を読み込む。
  3. malloc を使用して各単語のメモリを動的に確保する。
  4. ハッシュ法(チェイン法)を使用して単語の出現回数を関連付ける。
  5. ハッシュ関数は、すべての文字コードを加算し、256の剰余を取る。
  6. ハッシュテーブルの内容をダンプし、各単語とその出現回数を表示する。

2. 設計分析 (日本語)

2.1. データ構造

主要なデータ構造は、ハッシュ衝突を処理するための連結リスト(チェイン)のノードを表す struct Item です。 hashtable は、これらの Item 構造体へのポインタの配列です。


struct Item {
    int count;       // 単語の出現回数
    char *word;      // 単語文字列へのポインタ(動的に確保)
    struct Item *next; // チェイン内の次のアイテムへのポインタ
};
struct Item *hashtable[256]; // グローバルなハッシュテーブル配列

良い点: 連結リストノードに struct Item を使用しているのは、チェイン式ハッシュの実装として標準的で適切です。グローバルな hashtable 配列はアクセスを簡素化します。

2.2. 主要な関数

良い点: 各論理ステップ(ハッシュ処理、文字列作成、アイテム作成、検索、ダンプ)に対して明確に定義された関数を持つモジュラー設計は、初心者にとって非常に優れています。コードの可読性と保守性を向上させます。

2.3. メモリ管理

create_string と create_item では、それぞれ単語と Item 構造体のメモリを割り当てるために malloc が使用されています。これは動的データを保存するために正しいです。

レビューポイント (メモリリーク): 現在の実装には、プログラム終了時に動的に割り当てられたメモリ(word 文字列と Item 構造体の両方)を解放するための free() 呼び出しが含まれていません。これはメモリリークにつながります。小さなデモプログラムでは許容されますが、リソースが限られており、長時間実行されるプロセスがメモリを使い果たす可能性がある組み込みシステムにとっては重要な側面です。堅牢なコードのためには、ハッシュテーブルを走査して割り当てられたすべてのメモリを解放するクリーンアップ関数が必要です。

2.4. エラー処理

ファイルオープン (fopen) の基本的なエラー処理と、`create_string`、`hash`、`create_item` におけるヌルポインタチェックが含まれています(`hash` のチェックはループ条件による暗黙的なものです)。`search_item` は見つからない場合に正しく `NULL` を返します。

レビューポイント (入力の堅牢性): fscanf(istream, "%99s", buffer) は最大99文字の単語を処理します。しかし、fscanf が読み込みに失敗した場合(例: 20回の繰り返しより前にEOFに達した場合や、無効なフォーマットの場合)、create_string(buffer) が未初期化または空の buffer で呼び出され、問題を引き起こす可能性があります。fscanf の戻り値をチェックする方が良いでしょう。


    for (int i = 0; i < 20; i++) {
        if (fscanf(istream, "%99s", buffer) != 1) { // 読み込みが成功したかチェック
            break; // これ以上単語が読み込めない場合はループを終了
        }
        key = create_string(buffer);
        if (key == NULL) { // malloc失敗の処理
            perror("Memory allocation failed for key");
            break;
        }
        chainhash(key);
    }
    

レビューポイント (create_string と create_item のヌルチェック): create_string は buffer が 0 の場合に明示的に 0 を返し、create_item は key が 0 の場合に 0 を返しますが、これらの 0 の戻り値は呼び出し元(main と chainhash)で常に処理されているわけではありません。これらの関数内で malloc が失敗した場合、`NULL` を返す可能性があり、その後のヌルポインタの逆参照につながる可能性があります。malloc の戻り値は常にチェックしてください。

2.5. ハッシュ関数

ハッシュ関数 total % 256 はシンプルです。ASCII文字の場合には機能しますが、汎用的なハッシュ関数としては、同じASCII値の合計を持つ単語(例: "ab" と "ba")で衝突しやすい傾向があります。

レビューポイント (ハッシュ関数の品質): より多様な入力と良好な分布のためには、より洗練されたハッシュ関数(例: 多項式ローリングハッシュ、FNV-1aなど)が有利です。現在の合計ベースのハッシュ関数は非常にシンプルですが、特に一般的な単語で多くの衝突を引き起こし、最悪の場合、すべての単語が同じバケットにハッシュされると search_item および chainhash のパフォーマンスが O(N) に低下する可能性があります。

2.6. グローバル変数

グローバル変数 hashtable、buffer、key の使用は、初心者にとってはパラメータの受け渡しを簡素化します。しかし、大規模なプロジェクトでは、保守性やスレッドセーフティの問題につながる可能性があります。

注意点 (グローバル変数): 組み込みシステムでは、直接メモリにアクセスするためや固定サイズのバッファのためにグローバル変数を適切に使用することが好まれる場合もありますが、スコープと潜在的な副作用に関するトレードオフを理解することが重要です。

3. テスト結果の分析 (日本語)

提供されたテスト結果は、いくつかの重大な問題を示しています。

4. 組み込み初心者への推奨事項 (日本語)

  1. メモリクリーンアップの実装: 組み込みシステムでは、メモリは貴重なリソースです。常に malloc と free をペアで使用してください。すべてのチェインを走査し、各 Item 構造体とその word 文字列を解放する関数(例: free_hashtable())を実装してください。
  2. 堅牢な入力読み込み: EOFに達したときに優雅に終了するように、20回の繰り返しをハードコーディングするのではなく、fscanf の戻り値を処理するようにメインループを変更してください。
  3. `malloc` の戻り値の検証: 常に malloc が NULL を返していないかチェックしてください。もし返している場合は、エラーを処理してください(例: メッセージを表示して終了する)。
  4. 文字エンコーディング: 日本語のような非ASCIIテキストを処理する場合、ワイド文字関数(`wchar_t`、`wprintf`、`wcslen`、`wcscpy`、`wcscmp`)を使用し、それに応じてハッシュ関数を調整する必要があります。または、UTF-8を使用する場合は、UTF-8対応の解析ライブラリが必要になります。簡単な単語カウントの場合、最初はASCII英語に固執するのが最適です。
  5. ハッシュ関数の改善: 現在のハッシュ関数は概念的には機能しますが、実際のシナリオでのパフォーマンスと分布を向上させるために、より堅牢なハッシュ関数を検討してください。
  6. 配列サイズの定数化: 256 を繰り返しハードコーディングする代わりに、#define HASH_MAX 256 を使用してください。これにより、コードの保守性が向上します。
  7. 変数のスコープ: `buffer` と `key` を `main` 内でローカルに宣言することを検討し、グローバル変数の使用を減らし、より良いカプセル化を促進してください。