繁体   English   中英

访问链表时的分段错误11

[英]Segmentation fault 11 when accessing linked list

我确定我搞砸了我的指针,或者可能是初始的NULL ,但我无法理解。

我正在尝试将链接列表写入文本文件:

write_out(node *ll){
    ofstream out;
    out.open("output.txt");
    if (!out.is_open()) exit(EXIT_FAILURE);

    cout << ll->value;

    //stuff to write out
}

和:

struct node {
    int value;
    node *next;
}

但是行cout << ll->value导致Segmentation fault: 11 ,我不明白为什么。

我已经注释掉了我实际写出的代码,因为这是无关紧要的,问题显然是我(缺乏)理解上面的工作方式。

我调用write_out(linkedlist) ,其中node* linkedlist指向第一个节点。

这发生在:

read_in(node *ll){
    ifstream data; //opened and checked open as above for out
    int v;
    ll = new node;
    node *tmp = ll;
    data >> tmp->value;
    while(data >> v){
        tmp->next = new node;
        tmp = tmp->next;
        tmp->value = v;
    }
    tmp->next = NULL;  //thanks @sharth
}

肯定没有留下ll = NULL

read_in(node *ll){

ll按值传递的参数 这意味着read_in中对它的任何更改都只是本地的,并且在它之外没有任何影响。 因此,在read_in完成后,指向列表头部的指针仍为NULL (假设您使用了初始化指针)。 因此,使用NULL参数调用write_out会取消引用NULL指针,这将导致您的SIGSEGV。

我可以猜测问题出在你将新节点添加到列表的功能中。

我认为你做了类似的事情

void add_node( node *n, int value );

node *linkedlist = NULL;

add_node( linkedlist, somevalue );

在这种情况下,函数内链表的任何更改都不会影响原始对象链表。 所以它仍然等于NULL。 所以当你尝试输出列表并使用时

cout << ll->value;

ll等于NULL。

只是一个简单的例子来补充@Michael Foukarakis指出的内容

#include<iostream>

void this_dont_change_ptr(int* a, int val){
    a = new int;
    *a = val;   
}

void this_changes_ptr_itself(int** a, int val){
    *a = new int;
    *(*a) = val; 
}

int main(){

    int *my_ptr = NULL;
    this_dont_change_ptr(my_ptr, 5);

    if(my_ptr == NULL){
        std::cout << "In fact, ptr is still NULL" << std::endl;
    }

    // What I do with allocated memo??

    // grants that my_ptr is NULL again
    my_ptr = NULL;  
    this_changes_ptr_itself(&my_ptr, 5);
    if(my_ptr == NULL){
        std::cout << "MUST never get here!" << std::endl;
    }
    else{
        std::cout << "Now we have a new value " << *my_ptr << std::endl;    
    }

    delete my_ptr;  

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM