TryBugHunt
goNull / UndefinedMedium

Ticket queue crashes when nobody is waiting

BugFind the bug and fix the code

What it should do

lastTicket(ids) builds a linked queue of support tickets and returns the ID at the back of the queue, or -1 if the queue is empty. lastTicket([101, 102, 103]) returns 103.

What happens instead

lastTicket([]) crashes with panic: runtime error: invalid memory address or nil pointer dereference.

package main

type ticket struct {
    id   int
    next *ticket
}

func buildQueue(ids []int) *ticket {
    var head *ticket
    for i := len(ids) - 1; i >= 0; i-- {
        head = &ticket{id: ids[i], next: head}
    }
    return head
}

func lastTicket(ids []int) int {
    t := buildQueue(ids)
    for t.next != nil {
        t = t.next
    }
    return t.id
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the null and undefined errors pattern

A nil pointer or nil map that the code uses as if it held a value.

What you'll practise

A medium Go debugging exercise about null and undefined errors: a nil pointer or nil map that the code uses as if it held a value.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

For an empty list buildQueue returns a nil *ticket, because the loop never creates a node. The walk then reads t.next on that nil pointer, which panics. The loop condition checks the next node but never the current one. Any function that receives a pointer from somewhere else, especially the head of a list or a lookup result, should handle nil before touching a field. The empty case is the first test to write for anything built from a list.

The pattern behind it: null and undefined errors.

More null and undefined errors to practise

Related errors

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/1eefe882-70fd-4a93-abf3-05f4f986f5f6" title="Debugging challenge: Ticket queue crashes when nobody is waiting" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/1eefe882-70fd-4a93-abf3-05f4f986f5f6">TryBugHunt</a></p>