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()
之前。
你有什麼編譯您使用的是這個代碼在不同的文件中,同樣的頭,你是否從鏈接器收到任何警告......等 – Hogan 2012-08-11 18:48:37
你嘗試過使用'gdb'嗎? – Prasanth 2012-08-11 18:55:36
我做了一些類似的事情,因爲我使用了一堆printfs來跟蹤代碼。我還沒有學過gdb。只需重新訪問C即可幫助朋友。 – cesar 2012-08-11 19:02:02