Reputation: 19
I wrote the following code:
#include<stdio.h>
struct student{
char name[25];
double gpa;
struct student *next;
};
struct student *list_head;
struct student *create_new_student(char nm[], double gpa)
{
struct student *st;
printf("\tcreating node\t");
printf("\nName=%s \t Gpa= %.2f\n", nm, gpa);
st = (struct student*)malloc(sizeof (struct student ));
strcpy(st->name, nm);
st->gpa = gpa;
st->next = NULL;
return st;
}
void printstudent(struct student *st)
{
printf("\nName %s,GPA %f\n", st->name, st->gpa);
}
void insert_first_list(struct student *new_node)
{
printf("\nInserting node: ");
printstudent(new_node);
new_node->next = list_head;
list_head = new_node;
}
struct student *delete_first_node()
{
struct student *deleted_node;
printf("\nDeleting node: ");
printstudent(deleted_node);
list_head = list_head->next;
return deleted_node;
}
void printlist(struct student *st)
{
printf("\nPrinting list: ");
while(st != NULL) {
printstudent(st);
st = st->next;
}
}
int main()
{
struct student *other;
list_head = create_new_student("Adil", 3.1);
other = create_new_student("Fatima", 3.8);
insert_first_list(other);
printlist(list_head);
other = delete_first_node();
printlist(list_head);
return 0;
}
When I run it, there are no errors or warnings. However, it stops at the delete part.The message says the program has stopped working.
Can you please help me find the problem?
Upvotes: 0
Views: 48
Reputation: 106002
In function delete_first_node
the node deleted_node
is not initialized and passed to function printstudent
which try to access its member, results in undefined behavior.
The function should be
struct student *delete_first_node(){
struct student *deleted_node = list_head;
printf("\nDeleting node: ");
if(deleted_node != NULL)
{
printstudent(deleted_node);
list_head= list_head->next;
free(deleted_node);
}
else
printf("List is emty\n");
return list_head;
}
Upvotes: 1