如何防止结构被破坏?

时间:2012-03-31 23:41:38

标签: c

我迫切需要帮助。我已经在这方面工作了20多个小时。基本上我能够将信息扫描到结构中,但在功能完成后它会被破坏。我需要它去主要。我怎么能这样做?

struct tracks_{
  char *tracks_title;
  int playlist_hits;
};

struct album_ {
  int num_tracks;
  int *tracks;
};

typedef struct album_ album;
typedef struct tracks_ tracks;

album *pharse_album(FILE *album_file,int *number_of_albums){

  int number_of_album,number_of_tracks,number_of_charaters;
  int i,j;

  /*Gets the first number, which tell me how much albums there are*/
  fscanf(album_file,"%d", &number_of_album);

  album *all_albums_p = (album *)malloc(sizeof(album)*number_of_album);

  for(j=0;j<number_of_album;j++){
    for(i=0;i<all_albums_p[j].num_tracks;i++){
        /*This number tell me how many characters there are*/
        fscanf(album_file,"%d", &number_of_charaters);

        /*allocates memory*/
        all_albums_p[j].tracks = (int *)calloc(all_albums_p[j].num_tracks,sizeof(int));
        all_albums_p[j].tracks[i] = (char *)calloc(number_of_charaters+6,sizeof(char));


        fscanf(album_file, "%[^\n]s", all_albums_p[j].tracks[i]);

        /*Prints the tracks perfectly*/
        printf("%s\n",all_albums_p[j].tracks[i]);

        /*Sets playlist_hits 0*/
        all_tracks_p[i].playlist_hits = 0;
    }
  }
    return all_albums_p;
}

main(){
  int *number_of_albums,a;

  album *all_tracks_ptr;

  all_tracks_ptr = pharse_album(album_file,number_of_albums);

  int number_of_tracks[*number_of_albums];

    for(i=0; i < *number_of_albums ;i++){
      printf("%d : %d\n",i,all_tracks_ptr[i].num_tracks);

      /*Where the errors falls*/
      printf("%s",all_tracks_ptr[1].tracks[1]);

    }


    transaction(transaction_file);
  }
}

1 个答案:

答案 0 :(得分:4)

all_albums_p[j].tracks = (int *)calloc(all_albums_p[j].num_tracks,sizeof(int));

这将在i的每次迭代中执行,分配新内存并将旧内存与其存储的数据一起泄漏。你必须从内循环中移出它。

另一个主要问题是你没有返回专辑的数量,例如:

*number_of_albums = number_of_album;