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.
tom.txt) using fopen.malloc.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.
int hash(char *key): Calculates the hash value. Simple and effective for demonstration.char* create_string(char* buffer): Allocates memory for a string and copies content. Crucial for dynamic memory management.struct Item* create_item(char *key, struct Item *next): Creates a new Item node.void print_list(struct Item *item): Prints a single linked list (chain).void dump_ht(): Iterates through the hash table and calls print_list for non-empty buckets.struct Item *search_item(char *key, struct Item *item): Searches for a word within a given chain.void chainhash(char *key): The main function for inserting/updating words in the hash table, encapsulating the hashing, searching, and item creation/update logic.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.
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.
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`.
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.
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.
The provided test results highlight several critical issues:
このレポートは、英文テキストファイルを読み込み、各単語の出現回数をカウントし、チェイン式ハッシュ衝突解決戦略を持つハッシュテーブルを使用して結果を表示するCプログラムのレビューを行います。ハッシュ関数は、単語内の文字のASCII値を合計し、256の剰余を取る方法を使用しています。
tom.txt) を fopen で開く。malloc を使用して各単語のメモリを動的に確保する。主要なデータ構造は、ハッシュ衝突を処理するための連結リスト(チェイン)のノードを表す struct Item です。 hashtable は、これらの Item 構造体へのポインタの配列です。
struct Item {
int count; // 単語の出現回数
char *word; // 単語文字列へのポインタ(動的に確保)
struct Item *next; // チェイン内の次のアイテムへのポインタ
};
struct Item *hashtable[256]; // グローバルなハッシュテーブル配列
良い点: 連結リストノードに struct Item を使用しているのは、チェイン式ハッシュの実装として標準的で適切です。グローバルな hashtable 配列はアクセスを簡素化します。
int hash(char *key): ハッシュ値を計算します。デモンストレーションとしてはシンプルで効果的です。char* create_string(char* buffer): 文字列のメモリを確保し、内容をコピーします。動的なメモリ管理に不可欠です。struct Item* create_item(char *key, struct Item *next): 新しい Item ノードを作成します。void print_list(struct Item *item): 単一の連結リスト(チェイン)を表示します。void dump_ht(): ハッシュテーブルを走査し、空でないバケットに対して print_list を呼び出します。struct Item *search_item(char *key, struct Item *item): 指定されたチェイン内で単語を検索します。void chainhash(char *key): ハッシュテーブルに単語を挿入/更新する主要な関数で、ハッシュ処理、検索、アイテム作成/更新ロジックをカプセル化しています。良い点: 各論理ステップ(ハッシュ処理、文字列作成、アイテム作成、検索、ダンプ)に対して明確に定義された関数を持つモジュラー設計は、初心者にとって非常に優れています。コードの可読性と保守性を向上させます。
create_string と create_item では、それぞれ単語と Item 構造体のメモリを割り当てるために malloc が使用されています。これは動的データを保存するために正しいです。
レビューポイント (メモリリーク): 現在の実装には、プログラム終了時に動的に割り当てられたメモリ(word 文字列と Item 構造体の両方)を解放するための free() 呼び出しが含まれていません。これはメモリリークにつながります。小さなデモプログラムでは許容されますが、リソースが限られており、長時間実行されるプロセスがメモリを使い果たす可能性がある組み込みシステムにとっては重要な側面です。堅牢なコードのためには、ハッシュテーブルを走査して割り当てられたすべてのメモリを解放するクリーンアップ関数が必要です。
ファイルオープン (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 の戻り値は常にチェックしてください。
ハッシュ関数 total % 256 はシンプルです。ASCII文字の場合には機能しますが、汎用的なハッシュ関数としては、同じASCII値の合計を持つ単語(例: "ab" と "ba")で衝突しやすい傾向があります。
レビューポイント (ハッシュ関数の品質): より多様な入力と良好な分布のためには、より洗練されたハッシュ関数(例: 多項式ローリングハッシュ、FNV-1aなど)が有利です。現在の合計ベースのハッシュ関数は非常にシンプルですが、特に一般的な単語で多くの衝突を引き起こし、最悪の場合、すべての単語が同じバケットにハッシュされると search_item および chainhash のパフォーマンスが O(N) に低下する可能性があります。
グローバル変数 hashtable、buffer、key の使用は、初心者にとってはパラメータの受け渡しを簡素化します。しかし、大規模なプロジェクトでは、保守性やスレッドセーフティの問題につながる可能性があります。
注意点 (グローバル変数): 組み込みシステムでは、直接メモリにアクセスするためや固定サイズのバッファのためにグローバル変数を適切に使用することが好まれる場合もありますが、スコープと潜在的な副作用に関するトレードオフを理解することが重要です。
提供されたテスト結果は、いくつかの重大な問題を示しています。
malloc と free をペアで使用してください。すべてのチェインを走査し、各 Item 構造体とその word 文字列を解放する関数(例: free_hashtable())を実装してください。fscanf の戻り値を処理するようにメインループを変更してください。malloc が NULL を返していないかチェックしてください。もし返している場合は、エラーを処理してください(例: メッセージを表示して終了する)。256 を繰り返しハードコーディングする代わりに、#define HASH_MAX 256 を使用してください。これにより、コードの保守性が向上します。