Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang panic: runtime error: index out of range only happens when run outside debugger

I have the following code used to find two integers that sum to a given total in a given slice:

type Store_object struct {
    C      int
    I      int
    Prices []int
}
//..other unrelated functions...

func FindItemPairs(scenarios []Store_object) ([]string, error) {
    var results []string
    for scIndex := 0; scIndex < len(scenarios); scIndex++ {
        scenario := scenarios[scIndex]
        for prIndex := 0; prIndex < len(scenario.Prices); prIndex++ { //<--!sc
            firstItem := scenario.Prices[prIndex]
            if firstItem >= scenario.C {
                continue
            }
            for cmpIndex := prIndex + 1; cmpIndex < len(scenario.Prices); cmpIndex++ {
                secondItem := scenario.Prices[cmpIndex]

                switch {
                case secondItem >= scenario.C:
                    continue
                case firstItem+secondItem == scenario.C:
                    result := "Case #" + strconv.Itoa(scIndex+1) +
                        " " + strconv.Itoa(firstItem) + " " +
                        strconv.Itoa(secondItem)
                    results = append(results, result)
                }
            }
        }
   }
   return results, nil
}

however, when I attempt to run my code to find the item pairs, I get the following error:

panic: runtime error: index out of range

goroutine 1 [running]:
   <store_credit>.FindItemPairs(0x208208000, 0x1e, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0)
<store_credit_location>.go:76 +0x4ac 
main.main()
    <main_dir>/test_sc.go:16 +0x24d
exit status 2

(relevant line is noted with <--!sc above and <--!main below)

In order to try to debug, I used the following project https://github.com/mailgun/godebug to test, and found that my code executed without issue.

I currently have no clue how I would be accessing a value that is out-of-range, but have no idea how I will debug this further...

Any guidance on this would be greatly appreciated!

For more context, here is the code jam I'm trying to implement: https://code.google.com/codejam/contest/351101/dashboard#s=p0

Edit: For even more context, here is the main file I am running that calls this function:

func main() {
    cases, err := store_credit.ReadLines("A-small-practice.in")
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(cases)

    results, err := store_credit.FindItemPairs(cases) //<--!main
    if err != nil {
        fmt.Println(err)
    }

    for i := 0; i < len(results); i++ {
        fmt.Println(results[i])
    }
}

ReadLines works fine with no issues.

like image 816
jtgoen Avatar asked Jul 29 '15 04:07

jtgoen


1 Answers

It appears that you may have a data race somewhere. Try running it with the -race flag.

go run -race myfile.go

like image 81
Joshua Avatar answered Sep 23 '22 06:09

Joshua