试图获取vector迭代器的值时出现总线错误10



这是我用来构建链表的代码。

struct Node
{
    int data;
    struct Node *next;
};

Node* buildList(vector<int> &useThisVectorToBuildList)
{
    Node *newNode, *head, *tail;
   // vector<int> populateList(10,2,2,1,2,4,5);
    int vdata;
    for(vector<int>::iterator vecItr = useThisVectorToBuildList.begin(); vecItr!=useThisVectorToBuildList.end() ; vecItr++)
    {
        vdata = *vecItr;
        //create new node
        newNode = new Node;
        newNode->data = vdata;
        newNode->next = nullptr;
        // if first node - head - hasn't been created yet
        if(head==nullptr){
            head = newNode;
            tail = newNode;
        }
        else{
            tail->next = newNode;
            tail       = newNode;
        }
    }
    return head;
}

下面是我的main的样子(我只是想打印出头部节点的数据值):

/* ---------------------------- MAIN --------------------------------------- */
int main()
{
    vector<int> populateList{1,2,3,3,1,24,5};
    Node *listHead = buildList(populateList);
    cout << listHead->data  << endl;
    return 0;
}

对于迭代器的工作原理似乎缺乏理解。有了这段代码,当我执行代码时,我得到一个"总线错误:10"。

然而

如果我稍微更改现有代码(我只显示下面的更改):

Node* buildList(vector<int> &useThisVectorToBuildList)
{
   ...
    for(vector<int>::iterator vecItr = useThisVectorToBuildList.begin(); vecItr!=useThisVectorToBuildList.end() ; vecItr++)
    {
        vdata = *vecItr;
        cout << vdata << endl; // ADDED THIS LINE TO DEBUG and print value.
        //create new node
        newNode = new Node;
        newNode->data = *vecItr;
        newNode->next = nullptr;
       ...
    }
    return head;
}

我得到了输出:

1
Segmentation fault: 11

,如果我这样修改:

Node* buildList(vector<int> &useThisVectorToBuildList)
{
    Node *newNode, *head, *tail;
    for(vector<int>::iterator vecItr = useThisVectorToBuildList.begin(); vecItr!=useThisVectorToBuildList.end() ; vecItr++)
    {
        cout << *vecItr << endl; // ADDED THIS TO DEBUG. NOTE LACK OF TEMP VARIABLE "int vdata"
        //create new node
        newNode = new Node;
        newNode->data = *vecItr;
        newNode->next = nullptr;
    ...
    }
    return head;
}

我得到正确的输出。

1
2
3
3
1
24
5

1

为什么在将值赋给变量之前,我仅仅通过打印迭代器指向的值来看到正确的输出?

永远不要让变量初始化。在你的程序中,你有一个未定义的行为。

看这里:

Node *newNode, *head, *tail; // Unitialized pointers
[...]

// if first node - head - hasn't been created yet
if(head==nullptr){  // Which is the value of head? Unitiliazed, but probably different of nullptr
    head = newNode;
    tail = newNode;
}
else{
    tail->next = newNode;  // Using tail (which is unitialized) 
    tail       = newNode;
}

相关内容

  • 没有找到相关文章

最新更新