Reputation: 21
C Program crashes after last scanf/last loop, (trivia game).
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;
}
Upvotes: 1
Views: 105
Reputation: 16540
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) );
Upvotes: 1
Reputation: 53006
You must initialize *nrQ
first
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;
}
Also
malloc
fflush(stdin)
Upvotes: 0
Reputation: 13425
nRQ
is the input to the function and memory allocated based on this value
struct myQuiz *Quiz = (struct myQuiz*)malloc(sizeof (struct myQuiz)**nrQ);
Actual questions value is asked after the malloc, so if initial value passed to the function is less than questions, the memory corruption happens. you need to get the input first and then allocate the memory later.
printf("How many Questions?\n");
scanf_s("%d", nrQ);
Upvotes: 2