TheAlgorithms/Go · critical
BTree maxKeys cannot be zero
Error message
BTree maxKeys cannot be zero
What it means
NewBTreeNode panics when maxKeys is <= 0 because a B-tree node needs at least one key slot; the arrays keys and children would be meaningless otherwise. The library treats invalid construction parameters as a programming error, so it panics immediately rather than returning an error.
Source
Thrown at structure/tree/btree.go:26
type BTreeNode[T constraints.Ordered] struct {
keys []T
children []*BTreeNode[T]
numKeys int
isLeaf bool
}
type BTree[T constraints.Ordered] struct {
root *BTreeNode[T]
maxKeys int
}
func minKeys(maxKeys int) int {
return (maxKeys - 1) / 2
}
func NewBTreeNode[T constraints.Ordered](maxKeys int, isLeaf bool) *BTreeNode[T] {
if maxKeys <= 0 {
panic("BTree maxKeys cannot be zero")
}
return &BTreeNode[T]{
keys: make([]T, maxKeys),
children: make([]*BTreeNode[T], maxKeys+1),
isLeaf: isLeaf,
}
}
func NewBTree[T constraints.Ordered](maxKeys int) *BTree[T] {
if maxKeys <= 2 {
panic("Must be >= 3 keys")
}
return &BTree[T]{
root: nil,
maxKeys: maxKeys,
}
}
View on GitHub (pinned to 5ba447ec5f)
Solutions
- Pass a positive maxKeys >= 3 (a B-tree degree parameter) when constructing nodes.
- Validate any external/config-sourced value before calling NewBTreeNode.
- Use NewBTree(maxKeys) which enforces maxKeys >= 3 for the top-level entry point.
Example fix
// before
node := NewBTreeNode[int](cfg.MaxKeys, true)
// after
if cfg.MaxKeys < 3 { cfg.MaxKeys = 3 }
node := NewBTreeNode[int](cfg.MaxKeys, true) Defensive patterns
Strategy: validation
Validate before calling
func validMaxKeys(n int) bool { return n >= 3 }
if !validMaxKeys(cfg.MaxKeys) { cfg.MaxKeys = 4 }
node := NewBTreeNode[int](cfg.MaxKeys, true) Try / catch
func safeNewNode[T constraints.Ordered](maxKeys int, leaf bool) (n *BTreeNode[T]) {
defer func() {
if r := recover(); r != nil { n = nil }
}()
return NewBTreeNode[T](maxKeys, leaf)
} Prevention
- Never pass unvalidated config/env values as maxKeys
- Use NewBTree as the sole construction entry point
- Document that maxKeys is max keys per node, not tree order
When it happens
Trigger: Calling NewBTreeNode with maxKeys = 0 or a negative value, e.g. NewBTreeNode[int](0, true), or NewBTree (which calls it via Insert/Split paths) indirectly with a bad size derived from config or user input.
Common situations: Reading maxKeys from a config file or environment variable that is unset (0) or negative; off-by-one or integer division producing 0; copy-pasting a minimal example and passing 0 as a placeholder.
Related errors
- Must be >= 3 keys
- node has too few keys
- node has too many keys
- Called InsertNonFull() with a full node
- deleting out of bounds key
AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02).
Data as JSON: /api/errors/5fbb8bcbf74c984b.
Report an issue: GitHub.