2013-10-18 3 views
0

영화를 저장하고 구조체 배열에 동적 메모리 할당을 사용하는 라이브러리 프로그램을 만들었습니다. 첫 번째 레코드 (동영상) 추가 잘 작동하지만 두 번째 값을 그냥 엉망진 된 문자가 있습니다.배열 내부 함수의 realloc 구조체

내 코드를 보여주는 것보다 훨씬 더 말할 것도 없습니다.

문제는 그 내가 할 수없는 realloc 내 기능 addmovie();

내부하지만이 줄을 세우면 : 작동하는 것 같다 addmovie(); 함수를 호출하기 전에

movie = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies)); 

오른쪽, 왜?

/* Global variables */ 
int records = 0; // Number of records 

struct movies{ 
    char name[40]; 
    int id; 
}; 

addmovie(struct movies **movie) 
{ 
    int done = 1; 
    char again; 
    int index; 

    while (done) 
    { 
     index = records; 
     records++; // Increment total of records 

     struct movies *tmp = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies)); 

     if (tmp) 
      *movie = tmp; 

     system("cls"); 
     fflush(stdin); 
     printf("Enter name of the Movie: "); 
     fgets(movie[index].name, 40, stdin); 

     fflush(stdin); 
     printf("Enter itemnumber of the Movie: "); 
     scanf("%d", &movie[index].id); 

     printf("\nSuccessfully added Movie record!\n"); 

     printf("\nDo you want to add another Movie? (Y/N) "); 
     do 
     { 
      again = getch(); 
     } while ((again != 'y') && (again != 'n')); 

     switch (again) 
     { 
     case ('y'): 
      break; 

     case ('n'): 
      done = 0; 
      break; 
     } 
    } // While 
} 

int main() 
{ 
    int choice; 

    struct movies *movie; 
    movie = (struct movies *) malloc(sizeof(struct movies)); // Dynamic memory, 68byte which is size of struct 

    while (done) 
    { 
     system("cls"); 
     fflush(stdin); 
     choice = menu(); //returns value from menu 

     switch (choice) 
     { 
     case 1: 
      addmovie(movie); 
      break; 
     } 

    } // While 

    free(movie); // Free allocated memory 
    return 0; 
} 
+0

C 프로그램에서'malloc' 또는'realloc'의 반환 값을 캐스트 할 필요가 없습니다. –

+0

코드에서'records'를 증가시켜야합니다. – fritzone

+0

변수 입력이 완료된 후에'records'를 증가시킵니다. – Zn3

답변

3

C는 값에 의한 전달 언어입니다. 당신이 할 경우 :

movie = (struct movies *) realloc(movie, (records+1) * sizeof(struct movies)); 

을 함수에서 main()에서 movie는 전혀 영향을받지 않습니다.

void addmovie(struct movies **movie) 

다음 포인터의 내용을 수정합니다 : 그것은 다시 realloc의 반환 값을 할당하지 않는 것도 중요하다고

struct movies *tmp = realloc(...) 
if (tmp) 
    *movies = tmp; 

주 당신은 포인터 - 투 - 어 - 포인터를 전달해야 변수가 전달되면 - 결국 유출 될 수 있습니다.

자세한 설명은 comp.lang.c FAQ question 4.8을 확인하십시오.

+0

OP를 지적하는 데 도움이 될 수도 있습니다. 그는 실패 할 경우'realloc'의 반환 값을 검사하지 않고 원래 할당 된 메모리에 대한 포인터를 잃어버린 채 메모리 누수가 발생합니다. – Pankrates

+0

@Pankrates - 이미 완료되었습니다! –

+0

나는 당신에게서 아무것도 덜 기대하지 않았을 것이다. – Pankrates