【问题标题】:Is this reallocation method correct [duplicate]这种重新分配方法是否正确[重复]
【发布时间】:2017-12-08 15:37:37
【问题描述】:

我的代码有效,但我的问题是这种动态分配是否正确。它运行良好,一切正常,但我不太确定它是否正确。

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

【问题讨论】:

标签: c realloc


【解决方案1】:
temp_pStudents  = realloc(pStudents , sizeof(StudentDynamic) * (i + 1));
if (!temp_pStudents)
    // error
pStudents  = temp_pStudents ;

理想情况下应该是这样的。否则,如果发生错误,您会出现内存泄漏。这也使您免于取消对空指针的引用。

还有其他的东西包括

  • 强制转换malloc,这是不必要的。
  • 并使用带有while(!feof(file)) 的构造。不要使用它。查看评论中发布的讨论。

【讨论】:

  • temp_pStudents应该如何声明?
  • @Bogdy.: StudentDynamic *temp_pStudents .
  • 现在我崩溃了。请您检查一下是否需要? pastebin.com/kFGLRN54
  • @Bogdy.: 你的代码有未定义的行为。 fflush(stdin) 等...对其进行更改或提出适当的问题,甚至最好买一本书。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 2016-05-23
  • 2014-01-10
  • 1970-01-01
相关资源
最近更新 更多