2012-08-11 53 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