Exception thrown: read access violation. Head was nullptr.

Asked 2 years ago, Updated 2 years ago, 100 views

typedef struct node { int value; struct node* next; } } node; int ll_has_cycle(node* first) { node* head = first; while (head->next) { head = head->next; if (head == first) return 1; } return 0; } void test_ll_has_cycle(void) { int i; node nodes[5]; for (i = 0; i < sizeof(nodes) / sizeof(node); i++) { nodes[i].next = NULL; nodes[i].value = i; } nodes[0].next = &nodes[1]; nodes[1].next = &nodes[0]; nodes[2].next = &nodes[3]; printf("Checking first list for cycles. There should be a cycle, ll_has_cycle says it has % s cycle\n", ll_has_cycle(&nodes[0]) ? "a" : "no"); printf("Checking length-zero list for cycles. There should benone, ll_has_cycle says it has % s cycle\n", ll_has_cycle(NULL) ? "a" : "no"); printf("A node value is: %d", nodes[1].value); } int main(void) {

test_ll_has_cycle();
return 0;

} Code attempted to execute exception throw: read access violation. It says head was nullptr and it says segmentation_fault. What's wrong? ㅠ<

c exception gdb segmentation-fault

2022-09-20 19:57

1 Answers

When the part ll_has_cycle(NULL) is executed, an error occurs in while(head->next). If the head is NULL, this error occurs because the next cannot be accessed.

Modify to access head->next only when the head is not NULL.

Please refer to the code below.

#include<stdio.h>

typedef struct node
{
    int value;
    struct node* next;
} } node;

int ll_has_cycle(node* first)
{
    node* head = first;

    if (head != NULL)
    {
        while (head->next)
        {
            head = head->next;
            if (head == first)
                return 1;
        }
    }

    return 0;
}

void test_ll_has_cycle(void)
{
    int i;
    node nodes[5];
    for (i = 0; i < sizeof(nodes) / sizeof(node); i++)
    {
        nodes[i].next = NULL;
        nodes[i].value = i;
    }
    nodes[0].next = &nodes[1];
    nodes[1].next = &nodes[2];
    nodes[2].next = &nodes[3];
    nodes[3].next = &nodes[4];
    nodes[4].next = &nodes[0];
    printf("Checking first list for cycles. There should be a cycle, ll_has_cycle says it has % s cycle\n", ll_has_cycle(&nodes[0]) ? "a" : "no");
    printf("Checking length-zero list for cycles. There should benone, ll_has_cycle says it has % s cycle\n", ll_has_cycle(NULL) ? "a" : "no");
    printf("A node value is: %d", nodes[1].value);
}

int main(void) {
    test_ll_has_cycle();
    return 0;
}


2022-09-20 19:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.