Linked list segfaults when adding elements

Go To StackoverFlow.com

0

Why am I getting segmentation fault? I ran it with gdb and it crashing attail_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;
  }
}
2012-04-04 01:26
by Learning C


1

You have

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

What happens if curr_playlist -> next is NULL on the first iteration? Then tail_playlist is never set, but it is dereferenced on the next line:

tail_playlist -> next = p_playlist;
2012-04-04 01:31
by srgerg
Thank you so much - Learning C 2012-04-04 01:36
Ads