繁体   English   中英

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

您必须先初始化*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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM