0

I am trying to print the values of the single linked list in c, but its printing the garbage values after printing the values entered. I have written the create function to create the linked list by using the do-while loop, and also the display function to print the linked list. My question is why it is printing the garbage value after entering the values. Please help me to find out where I did wrong in my code to help further my coding practices.

Tried Code:

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

//Declaring the struct variable
struct Node
{
  int data;
  struct Node *link;
}*head=NULL;

//Creating the Linked List

void create()
{
  char ch= 'y';
  do
  {
    printf("ch : %c",ch);
    struct Node *p,*q;
    p = (struct Node*)malloc(sizeof(struct Node*));
    printf("\nEnter the Data : \n");
    scanf("%d", &p->data);
    p->link = NULL;
    if(head == NULL)
    {
      head = p;
    }
    else
    {
      q->link = p;
    }
    q=p;
    scanf("%c",&ch);
  }while(ch!= 'n');
}

//Displaying the Linked List

void display()
{
  struct Node *p=head;
  if(p == NULL)
  {
    printf("\n List is Empty \n");
  }
  else
  {
    while(p!=NULL)
    {
        printf("%d -->", p->data);
        p = p->link;
    }
  }
}

int main()
{
  printf("\n Enter the data into the linked list: \n");
  create();
  printf("\nCreation Complete........ Displaying\n");
  display();
  return 0;
}

Output:

1
2
3
4
5
6
n

Creation Complete........ Displaying
1 --> 2 --> 3 --> 4 --> 5 --> 6 -->7097656 -->
1
  • 1
    sizeof(struct Node*) is the size of a pointer to a node. You want to allocate a node. Remove the star. While you're at it, remove the cast of the return value of malloc. It doesn't help anything and in some circumstances can hide errors. Commented Nov 18, 2022 at 2:50

1 Answer 1

1

Here's an example on a 64-bit Windows host:

test.c:

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

struct Node
{
  int data;
  struct Node *link;
}*head=NULL;

int main(int argc, char* argv[])
{

  printf ("sizeof(struct Node): %lld, sizeof(struct Node*): %lld\n",
    sizeof(struct Node), sizeof(struct Node*));
  return 0;
}

Output:

sizeof(struct Node): 16, sizeof(struct Node*): 8

In other words, you probably want malloc(sizeof(struct Node)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.