Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

it seems like every guide is how to create LLL with ints, but I'm having trouble using char pointers. when i run this code, it segfaults immediately

here's my code thus far

struct node    
{
  char * data;
  node * next;   
};

void build(node * head);//create list    
void manipulate(node * & head);//manipulate list    
void display(node * head);//display all    
void delete_list(node * head);//delete all nodes in linked list    
bool again();//asks user if they'd like to continue

int main()
{
  node * head = NULL;
  //create list from user1 input
  while(again)
    build(head);
  //displays list
  display(head);
  //manipulate list as user2 reads through it
  manipulate(head);

  return 0;
}

void build(node * head)
{
  head->next = new node;
  char * data = new char;
  cout << "where to visit? ";
  cin.get(head->data,strlen(data)+1,'
');
  head = head->next;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
164 views
Welcome To Ask or Share your Answers For Others

1 Answer

I assume this code:

while(again)
    build(head);

Was meant to be (calling again instead of comparing it to zero):

while(again())
    build(head);

Either way, the first time through the loop head is NULL. But build goes ahead and uses it anyway:

head->next = new node;

Here, using next will produce a segment fault because head is NULL. You are accessing an invalid location in memory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...