2012-08-11 51 views
0

在調用從標準輸入讀取的任何內容時,我總是遇到分段錯誤。我不知道爲什麼。調用getchar()或某個函數內的任何其他類似函數會導致我的程序崩潰,但是當我從另一個函數調用它時,它工作正常。下面是崩潰的一部分:解析C中的標準輸入引起分段錯誤

int prompt() 
{ 
    int i; 
    int selection = -1; 
    while (selection < 0 || selection > 9) { 
    printf("Item:\n\n"); 
    for (i = 0 ; i < 10 ; i++) { 
     printf("%d) %s\n", i, getItemName(i)); 
    } 

    for (i = 0 ; i < 11 ; i++) { 
     printf("\n"); 
    } 

    printf("Select the number of the corresponding item: "); 
    char input = getchar(); <--- dies here! 
    if (input != EOF && input != '\n') flush(); 
    selection = atoi(input); <--- error here! 
    } 

    return selection; 
} 

void flush() { 
    char c = getchar(); 
    while (c != EOF && c != '\n') 
     c = getchar(); 
} 

UPDATE很多exprimenting之後,我發現這個問題是與我標出來的代碼。 (atoi())。我通過了一個簡單的char,而不是char*。我仍然不明白爲什麼當我使用一堆printfs時,它會死在我指定的線路上,而不是在撥打atoi()之前。

+0

你有什麼編譯您使用的是這個代碼在不同的文件中,同樣的頭,你是否從鏈接器收到任何警告......等 – Hogan 2012-08-11 18:48:37

+1

你嘗試過使用'gdb'嗎? – Prasanth 2012-08-11 18:55:36

+0

我做了一些類似的事情,因爲我使用了一堆printfs來跟蹤代碼。我還沒有學過gdb。只需重新訪問C即可幫助朋友。 – cesar 2012-08-11 19:02:02

回答

2

如果您使用調試器編譯並運行它,您會發現問題實際上是在您的atoi調用中。

char input = ...; 
... 
selection = atoi(input); 

atoi需要char *,所以你告訴它的字符串轉換地址0x00000030(爲'0')的數量,這是一個無效的地址。

在gdb

Select the number of the corresponding item: 0 

Program received signal EXC_BAD_ACCESS, Could not access memory. 
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000030 
0x00007fff8ab00c53 in strtol_l() 
(gdb) bt 
#0 0x00007fff8ab00c53 in strtol_l() 
#1 0x0000000100000dc5 in prompt() at test.c:45 
#2 0x0000000100000cb9 in main() at test.c:21 

與警告編譯也會告訴你:

$ gcc -Wall -std=gnu99 test.c 
test.c: In function ‘prompt’: 
test.c:48: warning: passing argument 1 of ‘atoi’ makes pointer from integer without a cast