添加元素时链接列表段错误

时间:2012-04-04 01:26:13

标签: c pointers linked-list segmentation-fault structure

为什么我会出现分段错误?我用gdb运行它,它在tail_playlist -> next = p_playlist;崩溃。

struct playlist_ {
  int album;
  int track_num;
  struct playlist_ *next;
};
typedef struct playlist_  playlists;

struct users_ {
  int user_ID;
  struct playlist_ *playlist;
  struct users_ *next;
};
typedef struct users_ users;

int add_playlist(users *user_pointer,int user_ID,int album_ID,int track_num){

  playlists *head_playlist,*tail_playlist,*curr_playlist,*p_playlist;
  users *curr_users;

  curr_users = user_pointer;
  while(curr_users){

    /* Find this user in link list */
    if(curr_users -> user_ID == user_ID){
      curr_playlist = curr_users -> playlist;

      /* Check if playlist is empty for this user if so, update the empty list*/
      if(curr_playlist -> album == NULL && curr_playlist -> track_num == NULL){
        curr_playlist -> album = album_ID;
        curr_playlist -> track_num = track_num;
        curr_playlist -> next = NULL;
      }else{

        /*Creates a new playlist node with the request album and track number*/
        p_playlist = (playlists *)malloc(sizeof(playlists ));
        p_playlist -> album = album_ID;
        p_playlist -> track_num = track_num;
        p_playlist -> next = NULL;

        /*Traverse Playlist, find the tail node*/
        for(curr_playlist = curr_users -> playlist; curr_playlist -> next; curr_playlist = curr_playlist -> next){

          /*Adds the playlist at the end*/

          tail_playlist = curr_playlist;
        };

        tail_playlist -> next = p_playlist;
      }
      break;
    }
    curr_users = curr_users -> next;
  }
}

1 个答案:

答案 0 :(得分:1)

你有

for (curr_playlist = curr_users -> playlist; curr_playlist -> next; curr_playlist = cure_playlist -> next){
    tail_playlist = curr_playlist;
}

如果第一次迭代curr_playlist -> nextNULL,会发生什么?然后永远不会设置tail_playlist,但会在下一行解除引用:

tail_playlist -> next = p_playlist;