1

I need help pointing *user_playlist to a playlist node. How can I do this?

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

struct users_ {
  int user_ID;
  playlists *user_playlist;
  struct users_ *next;
};
typedef struct users_ users;

p_users = (users *)malloc(sizeof(users *));
p_users -> user_ID = account_number;
head_users = p_users;
head_users -> next = NULL;
users_pointer = head_users;

p_playlists = (playlists *)malloc(sizeof(playlists));
curr_playlists = p_playlists;
curr_playlists -> album = NULL;
curr_playlists -> track_num = NULL;
curr_playlists -> next = NULL;
curr_users -> user_playlist = curr_playlists;

 users *head_users,*curr_users,*p_users,*users_pointer;
 playlists *head_playlists,*curr_playlists,*p_playlists,*playlist_pointer;
Learning C
  • 679
  • 10
  • 27
  • 1
    I'm getting Bus Error (core dumped) somewhere – Learning C Apr 03 '12 at 11:31
  • I think you need to write malloc(sizeof(users)) instead of malloc(sizeof(users*)). 'sizeof(users*)' means size of pointer to 'users', when you need size of 'users'. –  Apr 03 '12 at 11:33
  • @BinyaminSharet When I run it at gdb I get segmentation Fault right after here `curr_users -> user_playlist = curr_playlists;` – Learning C Apr 03 '12 at 11:35

1 Answers1

4

This is a problem:

p_users = (users *)malloc(sizeof(users *));

it only allocates the size of a pointer, not the size of a users structure. Change to:

p_users = malloc(sizeof(users));

or:

p_users = malloc(sizeof(*p_users));

Casting the return value of malloc() is unnecessary and potentially dangerous.

EDIT:

Dereferencing an unitialised, or NULL, pointer will cause a segmentation fault. This declares but does not initialise curr_users (same for other variables listed):

users *head_users,*curr_users,*p_users,*users_pointer;

An attempt is then made to access curr_users:

curr_users->user_playlist = curr_playlists; /* Segmentation fault. */

Initialise curr_users before using, to either a valid users structure or to NULL and check for non-null before deferencing:

users *head_users = NULL,*curr_users = NULL,
    *p_users = NULL,*users_pointer = NULL;

if (curr_users)
{
    curr_users->user_playlist = curr_playlists;
}
Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252