2017-12-08 8 views
1

내 코드는 작동하지만 제 질문은이 동적 할당이 올바른지 여부입니다. 그것은 잘 작동하고 모두 괜찮지 만 그것이 옳다는 것을 확신하지는 않습니다.이 재 할당 방법이 정확합니까?

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

[C에서 malloc() 및 패밀리의 반환 값을 캐스팅하지 않는 이유에 대한 설명을 참조하십시오.] (https://stackoverflow.com/q/605845/2173917) –

+2

[이유 "while (! feof (file))"항상 잘못 되었나요?] (https://stackoverflow.com/q/5431941/2173917) –

+0

왜 malloc + strcpy 대신에'strdup'를 사용하지 않으시겠습니까? –

답변

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

이상적이는 다음과 같이 될 것이다. 그렇지 않으면 오류가 발생하여 메모리 누수가 발생합니다. 또한 이것은 널 포인터를 derefrencing에서 당신을 저장합니다.

또 다른 일이

  • 이 필요하지 않은 malloc 캐스팅이 포함됩니다.
  • while(!feof(file))의 구문을 사용하십시오. 사용하지 마십시오. 의견에 게시 된 토론을 확인하십시오.
+0

temp_pStudents 어떻게 선언해야합니까? – Bogdy

+0

@Bogdy .:'StudentDynamic * temp_pStudents'. – coderredoc

+0

이제 충돌이 발생합니다 .. 원하시는 지 확인해 주시겠습니까? https://pastebin.com/kFGLRN54 – Bogdy