在链表C ++末尾插入时出现分段错误

时间:2017-03-29 04:01:38

标签: c++ linked-list segmentation-fault

好的,所以我试图通过逐个添加它们来创建一个链接的项目列表,我也想打印出结果。

我只显示我的部分代码(我需要处理的部分),因此请忽略我在此代码段中未真正使用的所有库:

#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

struct Item {
    char letter;
    Item *next;
};

class List {
  public:
    List();
    void InsertEnd(char key);
    void Display();
    bool IsEmpty();
    void SizeOf();
  private:
    Item *head;
    Item *tail;
    int size;
};

List::List() {
    head = NULL;
    tail = NULL;
    size = 0;
}

void List::InsertEnd(char key) {
    //new item we're adding to the end
    Item* addOn = new Item();
    addOn->letter = key;
    addOn->next = NULL;

    //temporary item to traverse through list
    Item* temp = head;

    //if list is empty, head and tail both point to it
    if ( IsEmpty() ) {
        head->next = addOn;
        tail->next = addOn;
    } else {
        //once temp = tail
        if (temp->next == NULL) {
            tail->next = temp;
            temp = addOn;
        }
    }

    //update size of list
    SizeOf();

}

void List::Display() {
    cout << "Items:" << endl;
    for (Item* curr = head->next; curr != NULL; curr = curr->next) {
      cout << curr->letter << endl;
    }

cout << size << " items." << endl;

}

bool List::IsEmpty() {
    if (size == 0)
        return true;
    else 
        return false;
}

void List::SizeOf() {
    size++;
}

int main() {
    List* test = new List;

    test->InsertEnd('A');
    test->InsertEnd('B');
    test->InsertEnd('C');

    test->Display();

    return 0;
}

它编译得很好,但是当我运行它时,字面上我唯一得到的就是&#34;分段错误。&#34; ???

2 个答案:

答案 0 :(得分:2)

如果列表为空,则head->next将为NULL,但您说head->next = addOn;。不应该是head = addOn;

事实上,整个代码块都是垃圾:

if ( IsEmpty() ) {
    // head and tail are both null so both of these lines
    // invoke undefined behavior (you cant say NULL->field = something)
    head->next = addOn;
    tail->next = addOn;
} else {
    //once temp = tail
    // temp = head. Shouldn't you just be putting "addOn" as the next item
    // in the list after tail? What if temp->next != NULL?
    if (temp->next == NULL) {
        // tail->next = head (because temp == head). That makes no sense.
        tail->next = temp;
        // So some temp variable = addOn? addOn doesn't actually go into the list?
        // Thats a memory leak right there.
        temp = addOn;
    }
}

在伪代码中你想要的是这样的:

if (IsEmpty())
{
    head = addOn;
    tail = addOn;
}
else
{
    // special case when 1 item in the list (i.e. head == tail)
    if (head == tail)
    {
        // new item comes after head
        head->next = addOn;
    }
    else
    {
        // new item comes after tail
        tail->next = addOn;
    }
    // tail is now the item just added.
    tail = addOn;
}

答案 1 :(得分:-1)

我建议您在调试器中单步执行,并在崩溃时确切地查看哪个值为null。调试器将显示代码中每个步骤的每个值。我已经编程了30多年,而且我每天都单步执行代码。