Search code examples
cstructdouble-pointer

Using double pointers in stuct


Let's say i have a student struct defined:

stuct student {
    struct Student *next;
};
typedef struct student Student

Now I have the following function:

void add_student(Student **student_list_ptr) {
    Student *new_s;
    new_s = malloc(sizeof(Student));

    // I want to insert this first the new_s into the student_list_ptr
    // I did this but it gives me a segmentation fault
    Student *current = *student_list_ptr;
    if (current->next == NULL){
        current->next = new_s;
    }
}

I want to insert this first the new_s into the student_list_ptr I did this but it gives me a segmentation fault.


Solution

  • Assuming you call your function like this:

    Student *list = NULL;
    ...
    add_student(&list);
    

    When you add the first element to the list, *student_list_ptr will be NULL. You then assign this to current (which is now also NULL) and try to dereference it. This is undefined behavior, and what caused the crash.

    If you always add new students to the front of the list, just make the new node the root and point the old root to it:

    void add_student(Student **student_list_ptr) {
        Student *new_s;
        new_s = malloc(sizeof(Student));
    
        new_s->next = *student_list_ptr;
        *student_list_ptr = new_s;
    }
    

    If on the other hand you want to add at the end, you first need to check if the root is NULL and if so make the new node the root:

    void add_student(Student **student_list_ptr) {
        Student *new_s;
        new_s = malloc(sizeof(Student));
        new_s->next = NULL;
    
        if (*student_list_ptr == NULL) {
            *student_list_ptr = new_s;
        } else {
            Student *current = *student_list_ptr;
            while (current->next != NULL){
                current = current->next;
            }
            current->next = new_s;
        }
    }