【发布时间】:2014-12-23 20:11:07
【问题描述】:
我有以下程序
#include <stdio.h>
#include "dbg.h"
#define MAX_DATA 100
typedef enum EyeColor{
BLUE_EYES, GREEN_EYES, BROWN_EYES, BLACK_EYES, OTHER_EYES
} EyeColor;
const char *EYE_COLOR_NAMES[] = {
"Blue", "Green", "Brown", "Black", "Other"
};
typedef struct Person {
int age;
char first_name[MAX_DATA];
char last_name[MAX_DATA];
EyeColor eyes;
float income;
} Person;
int main(int argc, char *argv[]){
Person you = {.age = 0};
int i = 0;
char *in = NULL;
printf("What's your First Name? ");
in = fgets(you.first_name, MAX_DATA-1, stdin); //fgets is much better
check(in != NULL, "Failed to read first name.");
printf("What's your Last Name? ");
in = fgets(you.last_name, MAX_DATA-1, stdin);
check(in != NULL, "Failed to read last name.");
printf("How old are you? ");
int rc = fscanf(stdin, "%d", &you.age);
check(rc > 0, "You have to enter a number.");
printf("What color are your eyes:\n");
for(i = 0; i <= OTHER_EYES; i++) {
printf("%d) %s\n", i+1, EYE_COLOR_NAMES[i]);
}
printf("> ");
int eyes = -1;
rc = fscanf(stdin, "%d", &eyes);
check(rc > 0, "You have to enter a number.");
you.eyes = eyes - 1;
//check(you.eyes <= OTHER_EYES && you.eyes >= 0, "Do it right, that's not an option."); // if you dont check this, seg fault can happen because of ...
printf("How much do you make an hour? ");
rc = fscanf(stdin, "%f", &you.income);
check(rc > 0, "Enter a floating point number.");
printf("------ RESULTS ------\n ");
printf("First Name: %s", you.first_name);
printf("Last Name: %s", you.last_name);
printf("Age: %d\n", you.age);
printf("Eyes: %s\n", EYE_COLOR_NAMES[you.eyes]);
printf("Income: %f\n", you.income);
return 0;
error:
return 1;
}
如果我跑了: $./ex24
我给出以下输入:
What's your First Name? a
What's your Last Name? b
How old are you? 1
What color are your eyes:
1) Blue
2) Green
3) Brown
4) Black
5) Other
> 1000
How much do you make an hour? 1
------ RESULTS ------
First Name: a
Last Name: b
Age: 1
Segmentation fault (core dumped)
此段错误是如何发生的?那不是枚举在我的内存中分配了应该可以容纳1000的int类型吗?
编辑 1:将一些文本格式化为代码。 编辑 2:注释掉检查。
【问题讨论】:
-
你的调试器说什么?
-
"正在分配我的内存中应该能够容纳 1000 的 int 类型?" – 噢,你对记忆的工作原理非常感到困惑。 (特别是,如果一个整数值不适合变量,那么高位就会被截断。)但我敢打赌,段错误不会仅仅因为分配给
enum类型的变量而引起。使用调试器! -
请发布
check函数。 -
@iharob:我们不需要看到
check函数。他输入了1000作为输入。他问为什么在删除对check的调用时代码会出现段错误。原因很清楚。
标签: c memory segmentation-fault