首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C 語言單詞統計程式除錯:指標初始化、記憶體管理與 strtok 迴圈邏輯修正

     編輯:程式設計綜合問答

主要錯誤與修正

  1. 字串指標初始化錯誤
    pStr = '\0'; → 應為 *pStr = '\0'; 或 pStr[0] = '\0';。原寫法將指標本身設為 NULL,導致後續 strlen(pStr) 觸發段錯誤。
  2. realloc 型別轉換
    pStr = (char)realloc(...) → 應為 pStr = (char*)realloc(...)。
  3. 單詞指標陣列寫入
    *(pWords + word_count) = (char*)malloc(...) → 正確。但原碼缺少型別轉換括號,建議統一 pWords[word_count] = malloc(...) 可讀性更高。
  4. strtok 迴圈邏輯缺陷
    原碼 while(pWord) { for(...) {...} } 缺少 pWord = strtok(NULL, delimiters); 在迴圈末尾,導致無限迴圈。需移至 if(new_word) 區塊外。
  5. bool 型別
    C99 前需 #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。
  • 釋放後指標置 NULL,防雙重釋放。

編譯建議

gcc -std=c11 -Wall -Wextra -pedantic -fsanitize=address -g wordcount.c -o wordcount

啟用 AddressSanitizer 可自動偵測緩衝區溢位、使用後釋放等記憶體錯誤。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved