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
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;
}
606 GDB gets version error when attempting to debug with the Presense SDK (IDE)
908 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
577 Understanding How to Configure Google API Key
581 PHP ssh2_scp_send fails to send files as intended
615 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.