0

调用从标准输入读取的任何内容时,我一直遇到分段错误。我不知道为什么。getchar()从某个函数中调用或任何其他类似函数会导致我的程序崩溃,但是当我从另一个函数调用它时,它工作正常。这是崩溃的部分:

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();
}

更新经过大量的实验,我发现问题出在我标记的代码上。(atoi())。我是通过它一个简单的char,而不是一个char*。我仍然不明白为什么当我使用一堆时printfs,它会死在我指定的行,而不是在调用atoi().

4

1 回答 1

2

If you compile and run it with a debugger, you will find that the problem is actually in your atoi call.

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

atoi takes a char *, so you are telling it to convert the string at address 0x00000030 (for '0') to a number, and that is an invalid address.

in 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

Compiling with warnings would also have told you this:

$ 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
于 2012-08-11T19:31:48.877 回答