bits-and-blooms/bitset

panic: runtime error: index out of range [67108863] with length 0

liqionghao opened this issue · 2 comments

The following go code gives panic.

panic: runtime error: index out of range [67108863] with length 0

goroutine 1 [running]:
github.com/willf/bitset.(*BitSet).Set(...)
/tmp/gopath698146075/pkg/mod/github.com/willf/bitset@v1.1.10/bitset.go:165
main.main()
/tmp/sandbox750448556/prog.go:17 +0x1e0

I have simple patch to fix the panic. Maybe the more proper fix is to change API of "Set" to "func (b *BitSet)(i, uint) (*BitSet, error)".

> diff --git a/bitset.go b/bitset.go
> index adfdf37..83129f6 100644
> --- a/bitset.go
> +++ b/bitset.go
> @@ -161,6 +161,9 @@ func (b *BitSet) Test(i uint) bool {
>  
>  // Set bit i to 1
>  func (b *BitSet) Set(i uint) *BitSet {
> +       if i >= Cap() {
> +               return b
> +       }
>         b.extendSetMaybe(i)
>         b.set[i>>log2WordSize] |= 1 << (i & (wordSize - 1))
>         return b

===== go code =====

package main

import (
	"fmt"
	"github.com/willf/bitset"
)

func main() {
	fmt.Println("Hello, playground")
	NumHosts := uint(32768)
	bmp := bitset.New(NumHosts)
	bmp.ClearAll()
	d := -1;

	fmt.Println("d is %d\n", uint(d))
	
	bmp.Set(uint(d))
}

You are correct that the the documentation is poor.

However, we don't want a silent failure, we do want a panic if you are passing bad inputs. If you have a bug in your code and you are passing bogus integers to the bitset, you should prefer to see your program crash and halt rather than to ignore the inputs silently... which can lead to very bad consequences (including security hacks).

I am closing this. A panic is the right behavior... please try the following...

var a = make([]byte, 5, 5)
a[7] = 0

This code will panic.

If you are trying to access non-existing data, you have a bug. You want to correct the bug. If you want to ignore the accesses, you can guard the calls in your code.