【发布时间】:2019-01-10 14:44:52
【问题描述】:
我正在为基础课程编写一个非常简单的 C 程序,我在第 14 行收到了EXC_BAD_ACCESS。我看不出问题出在哪里。
程序要求用户输入一个数字,然后显示与之关联的 ASCII 字符。
只有在使用lldb 调试我的程序时才会发生这种情况,AFAIK。从命令行或onlinegdb.com 运行时,它工作得非常好。
另外,如果我注释掉第 13 行,并将true 或false 分配给loop_ctrl,而不是UserWantsToExit 的返回值,则一切正常。
#include <stdio.h>
#include <stdbool.h>
void GetAndDisplayInput(void);
bool UserWantsToExit(void);
int main()
{
bool loop_ctrl = true;
while (loop_ctrl)
{
GetAndDisplayInput();
loop_ctrl = !UserWantsToExit(); /* EXC_BAD_ACCESS */
}
return 0;
}
void GetAndDisplayInput()
{
char input_char = '0';
printf("\nInput a number: ");
scanf("%i", &input_char);
getc(stdin); /* Gets rid of '\n' */
printf("\n\nIt's character '%c'!\n\n", input_char);
}
bool UserWantsToExit()
{
char choice = '0';
bool value = false;
printf("\nDo you want to exit? (Y/N): ");
scanf("%c", &choice);
getc(stdin); /* Gets rid of '\n' */
value = (choice == 'y' || choice == 'Y');
return value;
}
【问题讨论】:
-
您应该更正您的第一个 scanf,因为 %i 用于有符号整数并且您提供了一个字符,这是错误的。除此之外,您的代码似乎很好
标签: c macos exc-bad-access lldb