C 程序在最后一次输入后崩溃

C Program crashes after last input

C 程序在最后一个 scanf/last 循环后崩溃,(问答游戏)。

struct myQuiz*quizInput(int *nrQ)
{
    int i, nrofrecords = 0;
    struct myQuiz *Quiz = (struct myQuiz*)malloc(sizeof (struct myQuiz)**nrQ);

    printf("How many Questions?\n");
    scanf_s("%d", nrQ);

    for (i = 0; i < *nrQ; i++) //for-loop för att skriva in påståenden
    {
        printf("Trivia input: ");
        fflush(stdin);
        fgets(Quiz[i].qQuest, 100, stdin);
        nrofrecords = nrofrecords + 1;
        fflush(stdin);

        printf("Enter answer '1'(yes) or '0' (no): ");
        scanf_s("%d", &Quiz[i].qAns);
        fflush(stdin);

        printf("Enter the difficulty (1-5)?: ");
        scanf_s("%d", &Quiz[i].qDiff);


    }
    return Quiz;
}

nRQ是函数的输入和根据这个值分配的内存

struct myQuiz *Quiz = (struct myQuiz*)malloc(sizeof (struct myQuiz)**nrQ);

实际问题值是在 malloc 之后询问的,因此如果传递给函数的初始值小于问题,就会发生内存损坏。 你需要先获取输入,然后再分配内存。

printf("How many Questions?\n");
scanf_s("%d", nrQ);

你必须先初始化*nrQ

struct myQuiz*quizInput(int *nrQ)
{
    int i, nrofrecords = 0;
    struct myQuiz *Quiz; // = malloc(sizeof (struct myQuiz)**nrQ); you need to initialize *nrQ first

    printf("How many Questions?\n");
    scanf_s("%d", nrQ);

    Quiz = malloc(sizeof (struct myQuiz)**nrQ);
    for (i = 0; i < *nrQ; i++) //for-loop för att skriva in påståenden
    {
        printf("Trivia input: ");

        fgets(Quiz[i].qQuest, 100, stdin);
        nrofrecords = nrofrecords + 1;

        printf("Enter answer '1'(yes) or '0' (no): ");
        scanf_s("%d", &Quiz[i].qAns);

        printf("Enter the difficulty (1-5)?: ");
        scanf_s("%d", &Quiz[i].qDiff);
    }
    return Quiz;
}    

还有

  1. 不投malloc
  2. 不要fflush(stdin)
the code is using some trash from nrQ for the malloc 
before nrQ variable is set.

returned values from I/O statements 
must be checked to assure successful operation.

the user prompts fail to clearly indicate what the user is to input

suggest:

    printf("Please indicate how many Questions you will enter?\n");
    if(1 != scanf_s("%d", nrQ))
    { // then, scanf_s failed
        perror( "scanf_s for number questions failed" );
        return( NULL );
    }

    // implied else, scanf_s successful

    struct myQuiz *Quiz = NULL;
    if( NULL == (Quiz = malloc(sizeof (struct myQuiz)*(*nrQ)) )) )
    { // then, malloc failed
        perror( "malloc array of struct myQuiz failed" );
        return( NULL );
    }

    // implied else, malloc successful

    printf("\nNote: max question length: %d\n", sizeof(struct myQuiz.qQuest) );