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