Skip to content

Commit 9bda828

Browse files
Prevent is_circular from infinite loop (#179)
This commit refines the is_circular() to use slow and fast pointers instead of a single pointer iteration. The original approach struggled to detect mid-list loops without extra storage. The new method effectively identifies such loops, albeit with a minor increase in conditional checks, but without requiring additional storage.
1 parent 297bb61 commit 9bda828

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

qtest.c

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -875,17 +875,23 @@ static bool do_merge(int argc, char *argv[])
875875
static bool is_circular()
876876
{
877877
struct list_head *cur = current->q->next;
878+
struct list_head *fast = (cur) ? cur->next : NULL;
878879
while (cur != current->q) {
879-
if (!cur)
880+
if (!cur || !fast || !fast->next)
881+
return false;
882+
if (cur == fast)
880883
return false;
881884
cur = cur->next;
885+
fast = fast->next->next;
882886
}
883887

884888
cur = current->q->prev;
889+
fast = (cur) ? cur->prev : NULL;
885890
while (cur != current->q) {
886-
if (!cur)
891+
if (!cur || !fast || !fast->prev)
887892
return false;
888893
cur = cur->prev;
894+
fast = fast->prev->prev;
889895
}
890896
return true;
891897
}

0 commit comments

Comments
 (0)