I am trying to read from the while questions.txt which has the following format:
Question\n
Difficulty:Cost:Prize\n
Correct Answer\n
Answer 1\n
.
.
.
Answer i\n
\n
The following is a function that reads from questions.txt and stores it to a temporary node to be added to a linked list.
pQuestionType loadQuestions(pQuestionType pFirst)
{
pQuestionType pTemp = malloc(sizeof(pQuestionType));
FILE* pFile;
string sFilename, sTemp;
char cDump;
int nTemp, n=0;
gotoxy(0,0);
system("cls");
printf("Enter file name: ");
gets(sFilename);
pFile = fopen(sFilename, "rt");
while(!feof(pFile))
{
printf("Iteration \n");
fgets(sTemp, 255, pFile);
strcpy(pTemp->sQuestion, sTemp);
pTemp->sQuestion[strlen(sTemp)-1] = '\0';
printf("Add question success\n");
fscanf(pFile, "%d%c", &nTemp, &cDump);
pTemp->nDifficulty = nTemp;
printf("Add difficulty success\n");
fscanf(pFile, "%d%c", &nTemp, &cDump);
pTemp->nCost = nTemp;
printf("Add cost success\n");
fscanf(pFile, "%d%c", &nTemp, &cDump);
pTemp->nWinnings = nTemp;
printf("Add winnings success\n");
fgets(sTemp, 255, pFile);
strcpy(pTemp->sCorrect, sTemp);
pTemp->sCorrect[strlen(sTemp)-1] = '\0';
strcpy(pTemp->sAnswers[0], sTemp);
pTemp->sAnswers[0][strlen(sTemp)-1] = '\0';
printf("Add answer success\n");
for(n=1; n<10; n++)
{
fgets(sTemp, 255, pFile);
if(*sTemp == '\n')break;
strcpy(pTemp->sAnswers[n], sTemp);
pTemp->sAnswers[n][strlen(sTemp)-1] = '\0';
}
printf("Add choices success\n");
printf("\n");
pFirst = addQuestion(pFirst, pTemp);
if(*sTemp == EOF) break;
}
fclose(pFile);
return pFirst;
}
I crash at the third iteration when the program tries to read the difficulty of my third question. What causes this and what can I do to fix my code?
If
pQuestionTypeis a pointer type (and it appears to be since neitherpFirstnorpTemphave a*character anywhere near their declaration), then its size is going to be the size of a pointer (currently likely to be 4 or 8).So this
mallocwill almost certainly not give you enough memory. You need to usesizeof(*pTemp)instead.