pStr = '\0'; → 應為 *pStr = '\0'; 或 pStr[0] = '\0';。原寫法將指標本身設為 NULL,導致後續 strlen(pStr) 觸發段錯誤。
pStr = (char)realloc(...) → 應為 pStr = (char*)realloc(...)。
*(pWords + word_count) = (char*)malloc(...) → 正確。但原碼缺少型別轉換括號,建議統一 pWords[word_count] = malloc(...) 可讀性更高。
while(pWord) { for(...) {...} } 缺少 pWord = strtok(NULL, delimiters); 在迴圈末尾,導致無限迴圈。需移至 if(new_word) 區塊外。
#include ,或自行定義 typedef int bool; enum {false, true};。
char *pStr = malloc(str_size);
*pStr = '\0'; // 修正 1
while (fgets(buf, BUF_LEN, stdin)) {
if (buf[0] == '\n') break;
if (strlen(pStr) + strlen(buf) + 1 > str_size) {
str_size = strlen(pStr) + strlen(buf) + 1;
pStr = (char*)realloc(pStr, str_size); // 修正 2
}
strcat(pStr, buf);
}
char *pWord = strtok(pStr, delimiters);
while (pWord) { // 修正 4:迴圈結構
bool new_word = true;
for (int i = 0; i < word_count; ++i) {
if (strcmp(pWords[i], pWord) == 0) {
++pnWord[i];
new_word = false;
break;
}
}
if (new_word) {
if (word_count == maxWords) { /* realloc 擴容 */ }
pWords[word_count] = malloc(strlen(pWord) + 1);
strcpy(pWords[word_count], pWord);
pnWord[word_count++] = 1;
}
pWord = strtok(NULL, delimiters); // 關鍵:取下一個 token
}
malloc 對應一個 free。pWords[i] 逐一釋放後,再釋放 pWords、pnWord、pStr。gcc -std=c11 -Wall -Wextra -pedantic -fsanitize=address -g wordcount.c -o wordcount
啟用 AddressSanitizer 可自動偵測緩衝區溢位、使用後釋放等記憶體錯誤。