分段错误我不知道

时间:2015-06-23 18:26:28

标签: c segmentation-fault

我试图做一个简单的程序来保存我的标记并给我平均标记,但是当第二个函数结束时(并且当它结束时是exaclty,而不是重复时)它给了我分段错误,任何想法?

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "header.h"
void Iniz(std* x) {
     printf("insert name: "); gets(x->name);
     printf("insert surname: "); gets(x->surname);
     printf("insert matriculation number: "); scanf("%d",&(x->number));
     x->marksum = 0;
     x->exams = 0;
     x->average = 0.00f;
     }


void Mod(std* x) {
 char esame;
 printf("insert exam mark"); scanf("%d",&esame);
 x->marksum += esame;
 x->exams += 1;
 x->average = (x->marksum)/(x->exams);
 printf("add another one? (y/n) --> "); char c = getchar(); char ok = getchar();
 if (ok == 'y') Mod(x);
 }

int main() {
std* me = malloc(sizeof(std));
Iniz(me);
Mod(me);
printf("student: %s %s \nmatriculation number: %d \nExams done: %d \naverage mark: %f\n",me->name,me->surname,me->number,me->exams,me->average);
char ok = getchar();
char fine = getchar();
return 0;
}

file header.h

typedef struct {
    char name[20];
    char surname[20];
    unsigned int number;
    short int marksum;
    short int exams;
    float average;
    } std;

编辑:

是的,我使用了调试器,但只有在函数结束时才会出现错误。我的老师告诉我,我可以在char常量中保存很少的数字(从-127到126为char),他错了吗?为什么我只在函数结束时而不是之前,在scanf期间才得到错误?

1 个答案:

答案 0 :(得分:0)

执行此操作scanf("%d",&esame)并将esame定义为类型char时,您导致了未定义的行为。因为%d对应于带符号的十进制数字而不是字符,并且因为它对应的内存位置大于char的内存大小,scanf将覆盖旁边的数据您的堆栈上有esame,因为那是esame所在的位置。这可能会导致各种不良行为,其中一种是分段错误。

相关问题