following some forums and tutorials I wrote a code for sorted linked list. The code is causing core dump. I believe error is after line 50 where I'm trying to insert node at the end. Can you please help me with the bug? I'm not sure what I'm doing wrong. Thanks.
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct node
{
char val;
struct node* next;
};
struct node *start = (struct node*) NULL;
// definition of creating only first node
struct node* create(char* data)
{
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
if (start == NULL)
{
temp->val = data;
temp->next = NULL;
start = temp;
}
printf("List created\n");
}
struct node* insert(char* data)
{
int i, pos;
struct node* tempnode, *ptr;
ptr = start;
while(ptr != NULL)
{
if (data <= ptr->val)
{
printf("!!!Inserting before!!!\n");
tempnode = (struct node*)malloc(sizeof(struct node));
tempnode->val = ptr->val;
tempnode->next=ptr->next;
ptr->val = data;
ptr->next=tempnode;
break;
}
else if (data > ptr->val)
{
printf("!!!Going next!!!\n");
ptr = ptr->next;
}
if (ptr == NULL) //insert behind the node
{
tempnode = (struct node*)malloc(sizeof(struct node));
tempnode->val = data;
tempnode->next = NULL;
ptr->next = tempnode;
printf("!!!Placed at the end!!!\n");
break;
}
}
}
void display()
{
struct node* ptr; // ptr is pointer
ptr = start;
while (ptr != NULL)
{
printf("%s->", ptr->val);
ptr = ptr->next;
}
printf("End of list\n");
}
int main()
{
char* data;
int i = 0;
create(0);
FILE* file = fopen("words.txt", "r");
while (i < 10)
{
fscanf(file, "%s", &data);
printf ("data is %s\n", &data);
insert(data);
i++;
}
display();
}
-gflag to GCC), and run it in a debugger. The debugger will stop at the exact location of the crash, and let you see both the function call stack and let you examine values of variables. You should at least get the function call stack, and edit your question to include it.