-1

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    You aren't allocating any space for `node1.data` - it's just copying to an uninitialized pointer. – sj95126 Dec 28 '21 at 18:25
  • 1
    Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine at which point your program stops behaving as intended? If you did not try this, then you may want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Andreas Wenzel Dec 28 '21 at 18:26
  • Please check out the compiler warnings. There's also the crime of [returning the address of a local variable](https://stackoverflow.com/questions/22288871/function-returning-address-of-local-variable-error-in-c) with `return &x;` – Weather Vane Dec 28 '21 at 18:26
  • Basically you have lots of confusion about how to use pointers in C. You need to review your instructional material, SO is not a tutoring service. – Barmar Dec 28 '21 at 18:31

1 Answers1

0

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335