Is this reallocation method correct

时间:2017-12-08 15:37:37

标签: c realloc

My code works but my question is if this dynamic allocation is correct. It's works well and all is ok but I'm not so sure it is correct.

        StudentDynamic* pStudents = NULL;
        char auxfirstName[255], auxlastName[255];
        float auxGrade;
        FILE* pFile = fopen("InitialDB.txt", "r");
        if (pFile == NULL)
        {
            printf("Could not open file or is empty! Exiting...");
            exit(2);
        }
        int i = 0;
        pStudents = (StudentDynamic*)malloc(sizeof(StudentDynamic) * 1);
        while (!feof(pFile))
        {
            fscanf(pFile, "%s", auxfirstName);
            pStudents[i].firstName = (char*)malloc(strlen(auxfirstName) + 1);
            strcpy(pStudents[i].firstName, auxfirstName);

            fscanf(pFile, "%s", auxlastName);
            pStudents[i].lastName = (char*)malloc(strlen(auxlastName) + 1);
            strcpy(pStudents[i].lastName, auxlastName);

            fscanf(pFile, "%f", &auxGrade);
            pStudents[i].grade = auxGrade;

            i++;
            pStudents = (StudentDynamic*)realloc(pStudents, sizeof(StudentDynamic) * (i + 1));
        }
        nStudents = i;
        fclose(pFile);

1 个答案:

答案 0 :(得分:1)

temp_pStudents  = realloc(pStudents , sizeof(StudentDynamic) * (i + 1));
if (!temp_pStudents)
    // error
pStudents  = temp_pStudents ;

理想情况下,这将是这样的。否则,如果出现错误,则会出现内存泄漏。这也可以使您免于取消呈现空指针。

还有其他事情包括

  • 铸造malloc,这是不必要的。
  • 使用while(!feof(file))的构造。不要使用它。查看评论中发布的讨论。
相关问题