Project: p7A.c (2025/07/23)
Target Audience: Embedded Beginners
対象者: 組み込み初心者
This report provides a comprehensive design review of the C program `p7A.c` and its associated unit tests (`p7At1.c`, `p7At2.c`, `p7At3.c`). The program is designed to identify reverse-spelled word pairs within a given dictionary. This review aims to offer constructive feedback, highlight good practices, and suggest areas for improvement, particularly for embedded beginners. The full source code for each component is included for reference.
このレポートは、Cプログラム `p7A.c` および関連する単体テスト (`p7At1.c`、`p7At2.c`、`p7At3.c`) の包括的な設計レビューを提供します。このプログラムは、与えられた辞書内から倒語のペアを識別するように設計されています。このレビューは、建設的なフィードバックを提供し、良い習慣を強調し、特に組み込み初心者向けの改善点を提案することを目的としています。各コンポーネントの完全なソースコードが参照用に含まれています。
The program reads approximately 45,000 English words from "dict.txt", generates the reverse spelling (倒語) for each, and checks if the reversed word exists in the dictionary. If found, it displays the original word and its reverse. All dynamically allocated memory is freed upon program termination.
このプログラムは、"dict.txt" から約45,000語の英単語を読み込み、各単語の倒語を生成し、その倒語が辞書内に存在するかどうかを確認します。見つかった場合は、元の単語とその倒語を表示します。プログラム終了時には、動的に割り当てられたすべてのメモリが解放されます。
#include<stdio.h> // for printf
#include<stdlib.h> // for malloc, free
#include<string.h> // for strlen, strcpy, strcmp
char *word[50000]; //word charcter array MAX_WORDS 50000
char buffer[100]; // buffer foe read word MAX_WORD_LENGTH 99
char revkey[100]; // buffer revspell
int word_count = 0; // count for words
int word_size=0;
int total_size=0;
int revword_count=0;
int read_dict(); // read words from dic.txt.
char *revspell(char *key, char *revword); // cerate reverse word
char *search_all(char* key); // search reword from word
int main(){
if(read_dict()!=0){printf("error read"); return 0;};
printf("words:%d,size:%d\n",word_count,total_size);
for(int i=0; i< word_count; i++){
char *p = revspell(word[i], revkey);
*p='\0';
char *found =search_all(revkey);
if (found != 0) {
printf("rev:%s->%s\n",word[i],found);
//printf("%s\n",word[i]);
revword_count++;
}
}
printf("total revword:%d\n",revword_count);
for (int i = 0; i < word_count; i++) free(word[i]); //free memory
return 0;
};// end main
//-------------------------------------------------------
// 関数:read_dict,"dict.txt" ファイルから単語を読み込み、文字配列 word に格納する。
// 引数:なし
// 戻り値:正常に終了:0、 異常に終了:1
// word[]に単語を格納、word_count:単語数、total_size : メモリサイス
int read_dict(void){
FILE *istream;
istream = fopen("dict.txt", "r");
if (istream == 0){printf("can not open \n");return 1;}
while (word_count < 50000 && fscanf(istream, "%99s", buffer) == 1){
int word_size= strlen(buffer)+1;
word[word_count] = (char *)malloc(word_size);
strcpy(word[word_count],buffer);
word_count++;
total_size =total_size+ word_size;
}
fclose(istream);
return 0;
}//end read_dict
//-----------------------------------------。
//関数: revspell 与えられた単語(key) から倒語(revword) を生成する。
//引数: 単語 keyポインタ、 倒語 revwordのポインタ
//戻り値: 倒語 revwordの最後のポインタ
char *revspell(char *key, char *revword) {
if (*key == '\0') return revword;
revword = revspell(key + 1, revword);
*revword = *key;
return revword + 1;
};//end revspell
//-----------------------------------------
//関数:search_all 単語リストの中からkey 単語を探す
//引数: 探すkey単語、 単語リスト
//戻り値: リストが空の場合、値は見つからない0
// 見つかった場合: 単語リスト ポインタ
char* search_all(char* key) {
for (int i = 0; i < word_count; i++) {
if (strcmp( word[i], key) == 0) { // If strings are equal, strcmp returns 0
return word[i]; // Return a pointer to the found word
}
}
return 0;
}//end search_all
// テスト1 結果 dic.txtから45402語の単語を読み込み
// 正常に231語の倒語を生成した。(revspell)
/*
cd p729250724
gcc -c p7A.c -o p7A.o && ./p7A
words:45402,size:409048
total revword:231
...
...
rev:wolf->flow
rev:won->now
total revword:231
*/
//--------------------------------------------
//テスト2 結果 dictrev.txt 231語の倒語を読み込み
// 正常に231語の倒語を生成した。(revspell)
// dictrev.txt
// ah
// are
// bag
// ...
// ...
// wets
// wolf
// won
//結果
// words:231,size:1152
// rev:ah->ha
// rev:are->era
// rev:bag->gab
// ...
// rev:wets->stew
// rev:wolf->flow
// rev:won->now
// total revword:231
//--------------------------------------------
// テスト3 結果 dict.txt ファイルが存在しない場合の表示
// can not open
//-----------------------------------------------
// テスト4 結果 dict.txt 空ファイルの場合の表示
// words:0,size:0
// total revword:0 を表示する
//-----------------------------------------------
// テスト5 結果 dict.txt a 1文字 の場合の表示
//words:1,size:2
//rev:a->a
//total revword:1
//--------------------------------------------------
// テスト6 結果 dict.txt a 100文字 の場合の表示
//words:2,size:112
//total revword:0
// aが99文字と aが1文字の2単語と読むが
// revword は表示しない
//---------------------------------
Observations & Recommendations:
The main program successfully integrates the functions to find reverse word pairs. Error handling for file opening is present. The memory allocated by `malloc` is correctly `free`d at the end, which is excellent for embedded systems.
However, for performance, the linear search within a loop of 45,000 words means $45000 \times 45000$ comparisons in the worst case, which is very inefficient. This will be a significant bottleneck.
組み込み初心者への推奨事項:
メインプログラムは、倒語ペアを見つけるために各関数をうまく統合しています。ファイルオープンのエラー処理も行われています。`malloc` で割り当てられたメモリが最後に正しく `free` されている点は、組み込みシステムにとって非常に優れています。
ただし、パフォーマンスに関しては、45,000語のループ内で線形探索を行うと、最悪の場合 $45000 \times 45000$ 回の比較が発生し、非常に非効率です。これは重大なボトルネックとなるでしょう。
This test program (`p7At1.c`) verifies the functionality of the `read_dict()` function, which reads words from "dict.txt" and stores them in the `word` character array.
このテストプログラム (`p7At1.c`) は、"dict.txt" から単語を読み込み、`word` 文字配列に格納する `read_dict()` 関数の機能を検証します。
#include<stdio.h> // for printf
#include<stdlib.h> // for malloc, free
#include<string.h> // for strlen, strcpy, strcmp
char *word[50000]; //word charcter array MAX_WORDS 50000
char buffer[100]; // buufer foe read word MAX_WORD_LENGTH 99
int word_count = 0; // count for words
int total_size=0;
int read_dict(void);
void clean_word(void);
int main(){
//------------------------------------------------------
printf("Test1\n");
if (read_dict()!=0){printf("error1\n");}
printf("count:%d,size:%d\n",word_count,total_size);
//---------------------------------------------------
printf("Test2\n");
FILE *fp = fopen("dict.txt", "w");
if (fp == 0){printf("error21\n");}
fprintf(fp, "%s","");
fclose(fp);
if (read_dict()!=0){printf("error22\n");}
printf("count:%d,size:%d\n",word_count,total_size);
remove("dict.txt");
clean_word();
//----------------------------------------------------------
printf("Test3\n");
fp = fopen("dict.txt", "w");
if (fp == 0){printf("error31\n");}
fprintf(fp, "%s","flow\nloop\ncivic\n");
fclose(fp);
if (read_dict()!=0){printf("error32\n");}
printf("count:%d,size:%d\n",word_count,total_size);
remove("dict.txt");
clean_word();
//----------------------------------------------------------
printf("Test4\n");
fp = fopen("dict.txt", "w");
if (fp == 0){printf("error41\n");}
fprintf(fp, "%s","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n");
fclose(fp);
if (read_dict()!=0){printf("error42\n");}
printf("count:%d,size:%d\n",word_count,total_size);
remove("dict.txt");
clean_word();
//-----------------------------------------------------------
printf("Test5\n");
fp = fopen("dict.txt", "w");
if (fp == 0){printf("error51\n");}
fprintf(fp, "%s","aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n");
fclose(fp);
if (read_dict()!=0){printf("error52\n");}
printf("count:%d,size:%d\n",word_count,total_size);
remove("dict.txt");
clean_word();
//----------------------------------------------
printf("Test6\n");
fp = fopen("dict.txt", "w");
if (fp == 0){printf("error71\n");}
for (int i = 0; i < 50000; i++) fprintf(fp, "word%d\n", i);
if (read_dict()!=0){printf("error62\n");}
//for (int i = 0; i < 50000; i++) printf("%s ",word[i]);
printf("count:%d,size:%d\n",word_count,total_size);
fclose(fp);
remove("dict.txt");
return 0;
}//end main
//----------------------------------------
// 関数:read_dict,"dict.txt" ファイルから単語を読み込み、文字配列 word に格納する。
// 引数:なし
// 戻り値:正常に終了:0、 異常に終了:1
// word[]に単語を格納、word_count:単語数、total_size : メモリサイス
int read_dict(void){
FILE *istream;
istream = fopen("dict.txt", "r");
if (istream == 0){printf("can not open \n");return 1;}
while (word_count < 50000 && fscanf(istream, "%99s", buffer) == 1){
int word_size= strlen(buffer)+1;
word[word_count] = (char *)malloc(word_size);
strcpy(word[word_count],buffer);
word_count++;
total_size =total_size+ word_size;
}
fclose(istream);
return 0;
}//end read_dict
//-------------------------------------
//関数:clean_word word[50000] 初期化
//引数:なし
//戻り値:なし
//------------------------------------
void clean_word(void) {
for (int i = 0; i < 50000; i++) {
if (word[i] != 0) {free(word[i]);word[i] = 0; }
}
word_count = 0;total_size = 0;
}//end clean_word
// テスト 結果 期待した結果が得られた
// ただし test6 で word[] 50000単語 収納できなかった
//gcc p7At1.c -o p7At1 && ./p7At1
// Test1
// can not open
// error1
// count:0,size:0
// Test2
// count:0,size:0
// Test3
// count:3,size:16
// Test4
// count:1,size:100
// Test5
// count:2,size:102
// Test6
// count:49854,size:487425
//---------------------------------
Observations & Recommendations:
The test suite for `read_dict` is comprehensive and well-designed, covering various file states (non-existent, empty, valid) and word lengths. The use of `remove("dict.txt")` and `clean_word()` ensures a clean state for each test, which is excellent unit testing practice.
**Test 5 (100+ chars):** The result `count:2,size:102` for a 100-character word indicates `fscanf("%99s", ...)` correctly reads only the first 99 characters, and then the next character (newline or space) is treated as a new, 1-character word. This is expected behavior for `fscanf("%s")`.
**Test 6 (50,000 words):** The observation that only 49854 words were read instead of 50000 is important. This could be due to:
This test program (`p7At2.c`) verifies the functionality of the `revspell()` function, which generates the reverse spelling (`revword`) from a given word (`key`).
このテストプログラム (`p7At2.c`) は、与えられた単語 (`key`) から倒語 (`revword`) を生成する `revspell()` 関数の機能を検証します。
#include<stdio.h> // for printf
#include<stdlib.h> // for malloc, free
#include<string.h>
char *revspell(char *key, char *revword);
int main(){
//---------------------------------------------
printf("test1\n");
char key1[100] = "loop";
char revkey1[100]; // Make sure buffer is large enough
char *p1 = revspell(key1,revkey1);
*p1 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key1,revkey1);
//--------------------------------------------
printf("test2\n");
char key2[100] = "";
char revkey2[100]; // Make sure buffer is large enough
char *p2 = revspell(key2,revkey2);
*p2 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key2,revkey2);
//--------------------------------------------
printf("test3\n");
char key3[100] = "a";
char revkey3[100]; // Make sure buffer is large enough
char *p3 = revspell(key3,revkey3);
*p3 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key3,revkey3);
//--------------------------------------------
printf("test4\n");
char key4[100] = "ab";
char revkey4[100]; // Make sure buffer is large enough
char *p4 = revspell(key4,revkey4);
*p4 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key4,revkey4);
//--------------------------------------------
printf("test5\n");
char key5[100] = "abc";
char revkey5[100]; // Make sure buffer is large enough
char *p5 = revspell(key5,revkey5);
*p5 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key5,revkey5);
//--------------------------------------------
printf("test6\n");
char key6[100] = "abcdefghijklmnopqrstuvwxyz";
char revkey6[100]; // Make sure buffer is large enough
char *p6 = revspell(key6,revkey6);
*p6 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key6,revkey6);
//--------------------------------------------
printf("test7\n");
char key7[100] = "a b c";
char revkey7[100]; // Make sure buffer is large enough
char *p7 = revspell(key7,revkey7);
*p7 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key7,revkey7);
//--------------------------------------------
printf("test8\n");
char key8[100] = "123!@#$%()";
char revkey8[100]; // Make sure buffer is large enough
char *p8 = revspell(key8,revkey8);
*p8 = '\0'; // Manually null-terminate the reversed string
printf("rev:%s->%s\n",key8,revkey8);
return 0;
}//end main
//-------------------------------------------------
//関数: revspell 与えられた単語(key)から倒語(revword) を生成する。
//引数: 単語 keyポインタ、 倒語 revwordのポインタ
//戻り値: 倒語 revwordの最後のポインタ
char *revspell(char *key, char *revword) {
if (*key == '\0') return revword;
revword = revspell(key + 1, revword);
*revword = *key;
return revword + 1;
};//end revspell
// テスト結果 正常に動作することを確認した、
// test1
// rev:loop->pool
// test2
// rev:->
// test3
// rev:a->a
// test4
// rev:ab->ba
// test5
// rev:abc->cba
// test6
// rev:abcdefghijklmnopqrstuvwxyz->zyxwvutsrqponmlkjihgfedcba
// test7
// rev:a b c->c b a
// test8
// rev:123!@#$%()->)(%$#@!321
//---------------------------------------------------
Observations & Recommendations:
The `revspell` function is well-tested across a variety of inputs, including empty strings, single characters, and strings with special symbols. The recursive implementation is elegant and produces correct results. The manual null-termination in the `main` test is correctly applied.
組み込み初心者への推奨事項:
`revspell` 関数は、空文字列、単一文字、特殊記号を含む文字列など、さまざまな入力に対して十分にテストされています。再帰的な実装はエレガントで、正しい結果を生成します。テストの `main` での手動によるnull終端は正しく適用されています。
This test program (`p7At3.c`) verifies the functionality of the `search_all()` function, which searches for a key word within a list of words. It prepares a small dictionary for testing.
このテストプログラム (`p7At3.c`) は、単語リスト内からキー単語を検索する `search_all()` 関数の機能を検証します。テスト用に小さな辞書を準備します。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *word[10]; // 単語ああ
int count = 0;
char* search_all(char* key);
int main() {
char *test_words[] = {"ios", "android", "linux", "arduino", "raspi"};
for (int i = 0; i < 5; i++) {
word[i] = (char *)malloc(strlen(test_words[i]) + 1);
strcpy(word[i], test_words[i]);
count++; // Increment word_count for each word added
}
printf("Test dictionary %d words.\n", count);
printf("Words: ");
for(int i = 0; i < count; i++) { // Loop up to word_count
printf("%s%s", word[i], (i == count - 1) ? "" : ", ");
}
printf("\n");
//-------------------------------------------------------
printf("Test1\n");
char *key1 = "android";
char *found1 = search_all(key1);
if (found1 != NULL) { // Check for NULL before printing
printf("Test 1: '%s' found. : '%s'\n", key1, found1);
} else {
printf("Test 1: '%s' not found. \n", key1);
}
//--------------------------------------------------
printf("Test 2\n");
char *key2 = "windows";
char *found2 = search_all(key2);
if (found2 != NULL) {
printf("Test 2: '%s' found. Result: '%s' \n", key2, found2);
} else {
printf("Test 2: '%s' not found. Result: NULL (PASS)\n", key2);
}
//-----------------------------------------------------
printf("Test 3\n");
char *key3 = "LInux"; // Different case
char *found3 = search_all(key3);
if (found3 != NULL) {
printf("Test 3: '%s' found. Result: '%s' Fail\n", key3, found3);
} else {
printf("Test 3: '%s' not found. Result: NULL (PASS)\n", key3);
}
//---------------------------------------------
printf("Test 4\n");
char *key4 = "";
char *found4 = search_all(key4);
if (found4 != NULL) {
printf("Test 4: '%s' (empty string) found. Result: '%s' (FAIL)\n", key4, found4);
} else {
printf("Test 4: '%s' (empty string) not found. Result: NULL (PASS)\n", key4);
}
//------------------------------------
printf("Test 5\n");
char *key5 = "ios";
char *found5 = search_all(key5);
if (found5 != NULL) {
printf("Test 5: '%s' found. Result: '%s' (PASS)\n", key5, found5);
} else {
printf("Test 5: '%s' not found. Result: NULL (FAIL)\n", key5);
}
//---------------------------------------
printf("Test 6\n");
char *key6 = "raspi";
char *found6 = search_all(key6);
if (found6 != NULL) {
printf("Test 6: '%s' found. Result: '%s' (PASS)\n", key6, found6);
} else {
printf("Test 6: '%s' not found. Result: NULL (FAIL - expected to be found)\n", key6);
}
return 0;
}//end main
//-------------------------------------------------
//関数:search_all 単語リストの中からkey 単語を探す
//引数: 探すkey単語、 単語リスト
//戻り値: リストが空の場合、値は見つからない0
// 見つかった場合: 単語リスト ポインタ
char* search_all(char* key){
for (int i = 0; i < count; i++) {
if (strcmp( word[i], key) == 0) { // If strings are equal, strcmp returns 0
return word[i]; // Return a pointer to the found word
}
}
return 0; // Return NULL (0) if not found
}//end search
// テスト結果 正常に動作することを確認した.
// gcc p7At3.c -o p7At3 && ./p7At3
// Test dictionary 5 words.
// Words: ios, android, linux, arduino, raspi
// Test1
// Test 1: 'android' found. : 'android'
// Test 2
// Test 2: 'windows' not found. Result: NULL (PASS)
// Test 3
// Test 3: 'LInux' not found. Result: NULL (PASS)
// Test 4
// Test 4: '' (empty string) not found. Result: NULL (PASS)
// Test 5
// Test 5: 'ios' found. Result: 'ios' (PASS)
// Test 6
// Test 6: 'raspi' found. Result: 'raspi' (PASS)
Observations & Recommendations:
The `search_all` test suite is well-structured and covers common scenarios, including finding existing words (at various positions), not finding non-existent words, and demonstrating case sensitivity. The manual population of the `word` array for this test is appropriate for unit testing.
**Global Variable `count`:** Note that `search_all` in `p7At3.c` uses `int count` as a global variable, while the main `p7A.c` uses `int word_count`. While functionally similar, using consistent naming (`word_count` across all files) would improve clarity and maintainability.
組み込み初心者への推奨事項:
`search_all` のテストスイートはよく構成されており、既存の単語の検索(さまざまな位置)、存在しない単語の検索、大文字小文字の区別のデモンストレーションなど、一般的なシナリオをカバーしています。このテストのために `word` 配列を手動で設定している点は、単体テストとして適切です。
**グローバル変数 `count`:** `p7At3.c` の `search_all` では `int count` がグローバル変数として使用されていますが、メインの `p7A.c` では `int word_count` が使用されています。機能的には似ていますが、一貫した命名(すべてのファイルで `word_count`)を使用すると、明確さと保守性が向上します。
The `p7A.c` project demonstrates a strong foundation in C programming, with well-defined functions and a commendable approach to unit testing. The use of dynamic memory and recursive functions highlights a good understanding of core C concepts.
For embedded beginners, this project serves as an excellent learning experience, particularly in: