1

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);
Bogdy
  • 15
  • 3

1 Answers1

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

Ideally this would be something like this. Otherwise in case of error you have a memory leak. Also this saves you from derefrencing the null pointer.

Again other things include

  • casting malloc which is not necessary.
  • And using constructs with while(!feof(file)). Don't use it. Check the discussion posted in comment.
user2736738
  • 30,591
  • 5
  • 42
  • 56