2013-03-02 39 views
1

我試圖使用getline()從鍵盤獲取輸入,將其存儲在一個字符串中,將其標記化,然後打印令牌。當我運行這個時,在最後一次迭代(處理來自輸入的最後一個令牌的迭代)中出現Segmentation Fault錯誤。從getline令牌化輸入

#define _POSIX_C_SOURCE 200809L 
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <string.h> 

//////////////////////// 
// Main Method  // 
//////////////////////// 
void main() { 
    system("clear"); 
    int ShInUse = 1; // Represents if shell is in use 

    char curpath[1024]; // holds current path to print with prompt 
    char *UserCommand = NULL; 
    size_t combytes = 100; 
    UserCommand = (char *) malloc(combytes); 
    char *tok; 

    // Main loop that shell uses // 
    while (ShInUse == 1) { 
     getcwd(curpath, sizeof(curpath)); // Store initial working dir 
     printf("gash:%s>", curpath); // print prompt 

     getline(&UserCommand, &combytes, stdin); 
     tok = strtok(UserCommand, " \n"); // Tokenize input 
     if (tok == NULL) { 
      printf("Enter a command.\n"); 
     } else { 
      // Exit command // 
      if (strcmp(tok, "exit") == 0) { 
       ShInUse = 0; 
      } else { 
       while (tok != NULL) { 
        printf("You entered a command.\n"); 
        printf("tok: %s\n", tok); 
        tok = strtok(NULL, " \n"); 
       } 
      } 
     } 
    } 
    free(UserCommand); 
} 

任何有關可能導致這種情況的想法?調試目前不適合我。

+0

也許你忘了將UserCommand初始化爲NULL? – wildplasser 2013-03-02 19:36:02

+0

逐行註釋出代碼以準確查看段錯誤發生的位置。 – 2013-03-02 19:38:29

+0

@wildplasser感謝您的回覆。我嘗試過,但仍然無法工作。我忘了包括我的字符串declorations,我會將它們添加到我的帖子。 – Greg 2013-03-02 19:39:11

回答

3

我這個測試代碼:

#define _POSIX_C_SOURCE 200809L 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main() 
{ 
    char *UserCommand = NULL; 
    size_t combytes = 100; 
    UserCommand = (char *) malloc(combytes); 
    char *tok; 
    while(getline(&UserCommand, &combytes, stdin) != EOF) 
    { 
    tok = strtok(UserCommand, " \n"); // Tokenize input 
    if (tok != NULL) { 
     while(tok != NULL) { 
     printf("%s\n", tok); 
     tok = strtok(NULL, " \n"); 
     } 
    } 
    } 
    return 0; 
} 

並能正常工作的所有測試中,我已經做了 - 包括通過在源文件中作爲輸入,書寫相當長的線,等等,等等

所以我的結論是,你可能有東西在你的代碼段錯誤。

+0

+1在閱讀了getline()這個文檔之後,這段代碼似乎不再合理(雖然不需要「if(tok!= NULL)」)。我認爲你是對的。問題可能在其他地方。 – WhozCraig 2013-03-02 20:10:43

+0

嗨!爲什麼在While循環中使用getline(&UserCommand,&combytes,stdin)'。我理解OP需要'getline()'一次。 ** – 2013-03-02 20:12:28

+0

是的,爲了避免「刪除/添加」影響其行爲的某些東西,我採用了現有的代碼「儘管」,儘管我確實發現了「if」爲「不需要」 。 – 2013-03-02 20:12:55

0

而且不是一個答案,只是另一種選擇的編程風格:

每當我有一個符號化循環像你這樣,我寧願構建它們是這樣的:

for(tok = strtok(UserCommand, " \n"); 
    tok != NULL; 
    tok = strtok(NULL, " \n")) 
{ 
    printf("%s\n", tok); 
} 

這使關閉兩個strtok()電話一起並要求只寫NULL測試一次。你的方式很好,這只是另一種選擇。祝你好運!