0

我正在尝试从具有以下格式的 while questions.txt 中读取:

Question\n
Difficulty:Cost:Prize\n
Correct Answer\n
Answer 1\n
.
.
.
Answer i\n
\n

下面是一个从 questions.txt 中读取的函数,并将其存储到一个临时节点以添加到链表中。

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

当程序试图读取我的第三个问题的难度时,我在第三次迭代时崩溃了。是什么原因造成的,我可以做些什么来修复我的代码?

4

1 回答 1

1
pQuestionType pTemp = malloc(sizeof(pQuestionType));

如果pQuestionType是一个指针类型(它似乎是因为它们的声明附近既没有pFirstpTemp没有*字符),那么它的大小将是指针的大小(目前可能是 4 或 8)。

所以这malloc几乎肯定不会给你足够的内存。你需要sizeof(*pTemp)改用。

于 2012-12-08T14:38:39.560 回答