c++链表segfault调试

c++ linked list segfault debug

本文关键字:调试 segfault 链表 c++      更新时间:2023-10-16

我在C++中实现自己的linked_list时遇到了一个segfault。我花了几个小时在上面,但仍然无法找出错误。任何帮助都将不胜感激。提前谢谢。

我认为错误在find_kth1()函数中,但我不知道我做错了什么。我可以按预期打印链接列表。

/* 
 *
 * find kth to last element in a singly linked list
 */
#include <iostream>
// #include "../linked_list.h"
using namespace std; 
struct Node {
    int data ; 
    struct Node *next;
}; 
Node* push(Node *head, int d){ 
    // push to top
    Node *n = new Node; 
    n->data = d; 
    n->next = head;
    return n;
}

void print_LL( Node* head){ 
    Node* p = head;
    while(p) { 
        cout << p->data << ' '; 
        p = p->next; 
    }
} 
int find_length( Node* head) { 
    int len = 0; 
    Node* p = head; 
    while(p){
        len ++; 
        p = p->next;
    }
    return len;
}
Node* find_kth1( Node* head, int k){ 
    // find length, scan twice
    int len  = find_length(head);
    Node *p = head; 
    int i = 0;
    while( i < len-k){
        i ++ ;
        p = p->next;
    }
    return p;
}

int main( void){ 
    Node *head; 
    head = push( head, 2) ; 
    head = push( head, 3) ; 
    head = push( head, 4) ; 
    head = push( head, 5) ; 
    head = push( head, 2) ; 
    print_LL( head); 

    int k = 3;
    Node *p = find_kth1( head, k);
    // cout<<p->data<<endl;
} 

头指针需要初始化

它与未初始化一起使用

通常编译器会发出警告,所以总是要注意的警告

Node *head=NULL;