Home > Software engineering >  Why my stack implementation not working and giving the error "Segmentation fault (core dumped)&
Why my stack implementation not working and giving the error "Segmentation fault (core dumped)&

Time:11-26

Why my stack implementation not working and giving the error "Segmentation fault (core dumped)" Here is the code `

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};

int main()
{
    struct node *head, *newNode, *temp;
    head = 0;
    int choice=1;
    while(choice)
    {
        
        newNode = (struct node *)malloc(sizeof(struct node));
        printf("Enter Data: \n");
        scanf("%d", &newNode->data);
        newNode->next = 0;
        if (head == 0)
        {
            head=newNode;
        }
        else{
            temp->next=newNode;
            temp=newNode;
        }
        printf("Do You Want to Continue(0,1)?\n");
        scanf("%d",&choice);
        
        }

        temp=head;
        while(temp!=0){
            printf("%d",temp->data);
            temp=temp->next;
    }
    return 0;
}

I was trying to implement the LInked LIst but got the error "Segmentation fault (core dumped)"

CodePudding user response:

For starters you are not implementing a stack because you are not trying to add new nodes to the top of the stack. You are trying to implement just a singly-linked list.

As for the problem then in this else statement

    else{
        temp->next=newNode;
        temp=newNode;
    }

there is used the uninitialized pointer temo that has an indeterminate value. See its declaration

struct node *head, *newNode, *temp;

So this statement

temp->next=newNode;

invokes undefined behavior.

You need to initialize it in the if statement

    if (head == 0)
    {
        head=newNode;
        temp = head;
    }

If you want indeed to implement a stack then you should write instead of the if-else statement the following code

    newNode = malloc(sizeof(struct node));

    printf("Enter Data: \n");
    scanf("%d", &newNode->data);

    newNode->next = head;
    head = newNode;

In this case you will have the data structure LIFO (last input - first output).

Pay attention to that you should free all the allocated memory when the stack is not required any more. For example

while ( head != NULL )
{
    temp = head;
    head = head->next;
    free( temp );
}

CodePudding user response:

The error is in the line

temp->next=newNode;

You have to allocate space for temp or change temp to point to a block of memory that has already been allocated - temp is uninitialized, so it points to random memory. Since you haven't allocated memory for temp, changing temp->next is changing memory that belongs elsewhere, which results in a segmentation fault error.

Set it in

if (head == 0)
{
    head=newNode;
    temp = head=newNode;
}
  • Related