0

I am simply trying to create a linked list of characters. Here's the code:

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

struct node{
    char data;
    struct node *next;
};

void push(struct node** head,char ndata)
{
    struct node* temp=(struct node*)malloc(sizeof(node));
    temp->data=ndata;
    temp->next=(*head);
    *head=temp;
}

void display(struct node* head)
{
    struct node* temp=head;

    while(temp)
    {
        printf("%c ",temp->data);
        temp=temp->next;
    }   
}

int main()
{
    struct node* head;
    int a=1;
    push(&head,'a');
    push(&head,'b');
    push(&head,'c');
    push(&head,'b');
    push(&head,'a');

    display(head);  
    getch();
    return 0;
}

I am using push() function which inserts the values at head. And then using display() method to display the values in the list. When I execute the program, it says "program10.exe has stopped working". I don't understand what the problem is. Can anyone help?

2
  • 1
    sizeof(node) ? without a typedef? how?? Commented Feb 1, 2015 at 15:15
  • I am using Dev-CPP compiler. It automatically "attaches" typedef. Commented Feb 1, 2015 at 15:21

1 Answer 1

3

You didn't initialize head so it's not null but has a garbage value, so it doesn't stop the loop in the display function, and tries to dereference garbage there.

This:

struct node* head;

Should be:

struct node* head = NULL;
Sign up to request clarification or add additional context in comments.

1 Comment

Damn. How did I miss that? Thanks mate.

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.