Linked list new node at back (segmentation fault)

I have a book inventory link list with a node struct that has 4 data types (name, price, amount, ISBN). It lets me enter all information but when it prints, it shows the previous final node twice, then my new node successfully, but then a segmentation fault.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void inventory::insert_sorted(Node book) {
  Node *insert = new Node;

  insert->name = book.name;
  insert->price = book.price;
  insert->amount = book.amount;
  insert->ISBN = book.ISBN;

  if(head == NULL)
    head = insert;
  else {
    Node *tail = head;
    while(tail->next != NULL) {
      tail = tail->next;
    }
    tail->next = insert;
    }
}

void inventory::print() {
  Node *printer = head;

  cout << "Current Book Inventory:" << endl;

  while(printer->next != NULL) {
    cout << "Title : " << printer->name << endl;
    cout << "Price : " << printer->price << endl;
    cout << "Stock : " << printer->amount << endl;
    cout << "ISBN  : " << printer->ISBN << endl;
    cout << "---------------------" << endl;
    printer = printer->next;
  }
}
You don't show constructors of Node. I presume implicit default constructor. Constructors are convenient.

Here, you essentially want to copy the 'book' to the new Node, don't you? Let copy constructor do the work:
1
2
void inventory::insert_sorted( Node book ) {
  Node *insert = new Node { book };

However, your Node has a fifth member that your code does not explicitly initialize.
I bet the 'book' is no better, and thus the copy constructed Node will have the same issue.

What is the value of insert->next?
Lets make it explicit:
1
2
3
void inventory::insert_sorted( Node book ) {
  Node *insert = new Node { book };
  insert->next = nullptr;

(Prefer nullptr to NULL in modern C++.)
Topic archived. No new replies allowed.