Home > Net >  why does it show segmentation error in my code?
why does it show segmentation error in my code?

Time:12-29

this is the code for printing the two strings together but whenever I try to run it, there's a segmentation error but it compiles without any error, can anyone help?

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

typedef struct node
{
    char *data; //string data in this node
    struct node *next; //next node or NULL if none
} Node;
void print(Node *head); //function prototype print
Node *push_node(Node x, Node *strlist);
int main ()
{
    Node node1;
    Node node2;
    Node *list = NULL;
    strcpy(node1.data, "world");
    push_node(node1, list);
    strcpy(node2.data, "hello");
    push_node(node2, list);
    print(list);
return 0;
}
void print(Node *head)
{
    Node *p = head;
    while (p != NULL)
    {
        printf("%s", p->data);
        p = p->next;
    }
}
Node *push_node(Node x, Node *strlist)
{
    x.next= strlist;
    return &x;
}

CodePudding user response:

You declared two objects of the type Node

Node node1;
Node node2;

data members of which are not initialized. That is the pointers data of the objects have indeterminate values.

So calling the function strcpy

strcpy(node1.data, "world");
strcpy(node2.data, "hello");

results in undefined behavior.

Also the pointer list is not being changed within the program. It is always equal to NULL as it was initialized. So calling the function print does not make a sense.

To make your code at least working you need to make the following changes.

Node *push_node(Node *x, Node *strlist);

//...

node1.data = "world";
list = push_node( &node1, list);
node2.data = "hello";
list = push_node( &node2, list);
print(list);

//...

Node *push_node(Node *x, Node *strlist)
{
    x->next= strlist;
    return x;
}
  • Related