In the beginning you initialize a pointer to a node variable called
top
to null.
Then in your insert method you initialize variable
temp
( a pointer to a node ) with the pointer you got from allocating an appropriate sized memory chunk. Directly after that you overwrite that
temp
variable with the content of variable
top
(which is still null). After this you try to access elements within the node struct.
This explains your pains.
All you have to do is leave that statement out all together:
insert(int val)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->next = top;
top = temp;
}
Best Regards,
—MRB