OiO.lk Blog C++ How to Initialize the tail pointer in a Doubly Linked List for it to not give Segmentation Fault
C++

How to Initialize the tail pointer in a Doubly Linked List for it to not give Segmentation Fault


Now I have created a loop to make 25 nodes for the doubly linked list. By Initializing head pointer as NULL in the main function, now the forward_traversing and show_first functions do work as intended. But the tail value cannot by initialized NULL and I don’t know what to assign it or to change in this code to allow for the backward_traversing and show_last function to work.

During Debugging it throws Exception of "Segmentation Fault" in the functions:- backward_traversal and show_last.

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int value;
    struct Node *next_link;
    struct Node *prev_link;
} Node;

Node *create_node(int value)
{
    Node *new_node = malloc(sizeof(Node));
    new_node->value = value;
    new_node->next_link = NULL;
    new_node->prev_link = NULL;

    return new_node;
}

void forward_traversing(Node *head)
{
    Node *temp = head;

    while (temp != NULL)
    {
        printf("%d ", temp -> value);
        temp = temp->next_link;
    }
    printf("\n");
}

void backward_traversing(Node *tail)
{
    Node *temp = tail;

    while (temp != NULL)
    {
        printf("%d ", temp->value);
        temp = temp->prev_link;
    }
    printf("\n");
}

void show_first(Node *head)
{
    printf("%d is the first value\n", head->value);
}

void show_last(Node *tail)
{
    printf("%d is the last value\n", tail->value);
}

int main()
{
    Node *head = NULL , *temp = NULL , *tail = NULL;

    for (int i = 25; i >= 0; i--){
        temp = create_node(i);
        temp -> next_link = head;
        temp -> prev_link = tail;
        head = temp;
    }
    
    forward_traversing(head);
    backward_traversing(tail);
    show_first(head);
    show_last(tail);

    free(head);
    free(tail);
    free(temp);
    
    return 0;
}

I am currently trying to make several functions to insert at the start, end and in reference to another node and maybe somehow make that automate my making node process.

For OS I have Windows 11 and Compiler is GNU default compiler in Vs Code



You need to sign in to view this answers

Exit mobile version