I’m trying to create a linked list of student with the struct below.
struct student
{
int student_ID;
char *student_name;
struct course *courses_enrolled;
Student *child;
};
//Insert student to the list with a given student pointer and the starting point
Student *insert_student(Student *child, Student *root)
{
Student *temp = (Student*)malloc(sizeof(Student));
//if there isn't a starting point, declare this as the start point
if( root->student_name == NULL )
{
root->student_ID = child->student_ID;
root->student_name = strdup(child->student_name;);
root->child = NULL;
}
//if this student's name is before current node, replace node.
else if( strcmp( child->student_name, root->student_name ) < 0 )
{
temp = root;
root = child;
child->child = temp;
}
//if this student's name is after current node, keep doing insert recursion
else if( strcmp( child->student_name, root->student_name ) > 0 )
{
insert_student( child, root->child );
}
return root;
}
The first root insertion would always work fine but when I attempt to add the 2nd one, the program will seg fault after the 2nd call to insert_student. It fails at the comparison
if( root->student_name == NULL )
I suspect that is has something to do with me accessing the child node of the root (root->child) but i’m not really sure what.
p/s: I know I’m not deallocating, that’s just a temporary thing as I’m required to use a different library.
UPDATE: Removed excess code.
It is a bit difficult to find the exact problem for we are not given how this function is called. There seems to be a few things that you want to check.
I am assuming that the
childandrootthat you passed in to the function are indeed allocated, with all fields in root set toNULLand that student’s name are in order so that your second branch never happen. Then, the first insertion will work.But, when you do the second insertion. You are passing in
root->childwhich you have set toNULLin the firstifclause. This will led subsequentstrcmpto fail, because you cannot dereference fromNULL(e.g.NULL->student_namethrows an error).