Fix Go "panic: runtime error: makeslice: len out of range" — Negative Length, Length Past Capacity, and Sizes That Overflow
A length or a capacity reached make in a shape no slice can have: negative, past the capacity, or wrapped around by overflow into a negative number that looks nothing like the input that produced it. Below, each shape gets its own section: the exact output it prints, which of the two makeslice messages it earns and why, and the validation that has to happen before the make call — because at the make call it is already too late.
Written November 21, 2026 · Tested with Go 1.26.4 · 7 min read
- The legal shapes first: what a working make looks like
- The first failure: a negative length
- Length past capacity: constants fail to build, variables panic
- A negative capacity: the same cap message, a different wrong number
What this guide is
You hit panic: runtime error: makeslice: len out of range when make is asked to build a slice whose length cannot exist.
make for a slice takes a length and, optionally, a capacity: make(T, n) builds a slice of type T with length n and capacity n, and make(T, n, m) builds one with length n and capacity m. A slice's length is how many elements it holds now. Its capacity is how many elements fit in the underlying array before a new array is needed. At any time the relationship 0 <= len(s) <= cap(s) holds — so a length below zero, a length above the capacity, or a capacity below zero describes no slice at all, and make refuses by panicking at the call.
There are two messages, and which one prints tells you which number was wrong:
panic: runtime error: makeslice: len out of range— the length is negative, or so large that the allocation it implies cannot be made.panic: runtime error: makeslice: cap out of range— the capacity is negative, smaller than the length, or too large to allocate.
Why doesn't the compiler stop you? Sometimes it does — when the bad numbers are constants, as a later section shows. But a length computed from input, a header field, a database count, or arithmetic is not a constant. The compiler cannot know its value, so the code builds, and the runtime check inside make is the first thing that ever sees the real number. The panic happens at the make call itself, in the goroutine that called it, and the stack trace names that line — which is the one useful thing about this crash: the line in the trace is where the bad value was consumed, even though it is rarely where the bad value was born.
The shapes in this guide look similar in a stack trace. They aren't the same bug.
- A negative length? A count or a size came from somewhere that can go below zero — a subtraction, an error path, an untrusted field — and nobody checked its sign.
- A length past its capacity? Two numbers that were supposed to agree were computed separately, and one of them moved.
- A huge or wrapped size? Arithmetic overflowed, or an input was trusted as an allocation size. The number in the panic's neighborhood may look absurd precisely because it is not the number anyone typed.
All examples use Go 1.26.4. Each one is a single main.go in one module. Make the module once, from an empty directory:
$ mkdir makeslice
$ cd makeslice
$ go mod init example.com/makeslice
go: creating new go.mod: module example.com/makeslice
After that, swap in each program as the new main.go. Transcripts come from go run -trimpath main.go. The -trimpath flag shortens file paths in the trace — you see ./main.go:8 instead of a long absolute path. Line numbers match either way. Tested with Go 1.26.4.
The legal shapes first: what a working make looks like
Before the failures, the baseline. A two-argument make sets length and capacity to the same number. A three-argument make sets them separately, with the length no larger than the capacity. Both forms zero-fill the elements they create.
// main.go
package main
import "fmt"
func main() {
a := make([]int, 3)
b := make([]int, 3, 10)
fmt.Println(len(a), cap(a))
fmt.Println(len(b), cap(b))
fmt.Println(a)
fmt.Println(b)
}
$ go run -trimpath main.go
3 3
3 10
[0 0 0]
[0 0 0]
Read the two pairs. make([]int, 3) reports length 3, capacity 3 — ask for no extra room and you get none. make([]int, 3, 10) reports length 3, capacity 10: three elements exist now, and seven more can be appended before the slice has to move to a bigger array. Both print [0 0 0], because make initializes the memory it allocates — a fresh []int slice is full of zeros, not garbage.
Every failure below is one of these two calls with a number pushed outside the fence: length below 0, length above capacity, capacity below 0, or a size so large the runtime will not attempt it. Keep the fence in mind — 0 <= len(s) <= cap(s) — because each panic message is just the fence reporting which side was crossed.
The first failure: a negative length
Start small. Put a negative number in a variable, then use it as a length.
// main.go
package main
import "fmt"
func main() {
n := -1
fmt.Println("before")
s := make([]int, n)
fmt.Println(len(s))
}
$ go run -trimpath main.go
before
panic: runtime error: makeslice: len out of range
goroutine 1 [running]:
main.main()
./main.go:8 +0x65
exit status 2
before prints. Then the make call panics, and len(s) never prints because there is no s — make did not return a half-built slice, a nil slice, or an error. It panicked, and the whole program ends unless something recovers.
Note what made this shape possible: the -1 sits in a variable. The compiler sees a length of type int and nothing more; -1 is a perfectly good int. The value is only wrong for a length, and that is checked where lengths are consumed — inside make, at run time. Compare the constant version in its own section below: the same -1 written as a literal in the call is a compile error, and the program never runs at all.
In real code the negative rarely arrives as a literal either. It arrives as count - removed where removed was bigger, as a size parsed from a request that nobody range-checked, or as the wrapped result of arithmetic — the overflow section below is this same panic wearing that disguise. When you meet this message, do not stare at the make line. Print or log the length's inputs and walk back to where the number went negative; the make call is the victim, not the culprit.
Length past capacity: constants fail to build, variables panic
Ask for a length of 5 in a capacity of 3. Written with constants, this program never runs:
// main.go
package main
import "fmt"
func main() {
fmt.Println("before")
s := make([]int, 5, 3)
fmt.Println(len(s), cap(s))
}
$ go run -trimpath main.go
# command-line-arguments
./main.go:7:19: invalid argument: length and capacity swapped
That is a compile error, not a panic: invalid argument: length and capacity swapped. When both size arguments are constant, the specification requires the length to be no larger than the capacity, and the compiler enforces it — with a message that guesses you swapped the two arguments, which is the most common way this constant shape happens at a keyboard. There is no executable here, no stack trace, and nothing to debug at run time. Swap the numbers back or fix whichever one is wrong.
Now the same request with the numbers in variables — which is how the request actually arrives in a program that computes its sizes:
// main.go
package main
import "fmt"
func main() {
n := 5
c := 3
fmt.Println("before")
s := make([]int, n, c)
fmt.Println(len(s), cap(s))
}
$ go run -trimpath main.go
before
panic: runtime error: makeslice: cap out of range
goroutine 1 [running]:
main.main()
./main.go:9 +0x4b
exit status 2
Same intent, completely different death. The program builds, before prints, and the make call panics — and note the message. It is not the len out of range message from the title of this guide. It is makeslice: cap out of range. When the length exceeds the capacity, the runtime reports the capacity as the number that is out of range, because the capacity is what failed to contain the length. Expecting the word len in the message for this shape sends a search in the wrong direction; grep your logs for cap out of range as well.
This is the shape behind a classic production bug: a length derived from data — records actually read, bytes actually decoded — paired with a capacity derived from a header, a configuration value, or an earlier estimate. Each number is plausible alone. Together they violate the one rule, and the violation only exists at run time, in the values, where the compiler cannot see it. The fix is not to clamp silently at the make call. It is to decide, where the two numbers are produced, which one is authoritative — usually the length the data demands — and to size the capacity from it, or to drop the explicit capacity entirely and let the two-argument form or append handle growth.
A negative capacity: the same cap message, a different wrong number
The capacity can be the bad number on its own. Keep the length legal and push the capacity below zero:
// main.go
package main
import "fmt"
func main() {
n := 0
c := -1
fmt.Println("before")
s := make([]int, n, c)
fmt.Println(len(s), cap(s))
}
$ go run -trimpath main.go
before
panic: runtime error: makeslice: cap out of range
goroutine 1 [running]:
main.main()
./main.go:9 +0x5f
exit status 2
before prints, then panic: runtime error: makeslice: cap out of range at the make line. A capacity of -1 is out of range for the same reason a negative length is: no array has negative room. The message cannot tell you whether the capacity was negative, smaller than the length, or enormous — all three report as cap out of range — so the message alone does not finish the diagnosis. The values do. When this panic fires, the next step is always the same: get both numbers, the length and the capacity, printed or logged just before the call, and see which side of the fence the pair fell off.
Capacities usually go wrong more quietly than lengths. A length tends to be counted from real data. A capacity tends to be a hint — an estimate, a previous size, a value carried forward from a previous batch — and hints go stale. A capacity computed as previous - shrinkage, or read from a field that was never validated because "it is only a hint," is still a hard argument to make: the runtime does not grade hints on intent. If a capacity is only a hint in your design, the capped-hint pattern in the fixed program below is how to keep it one.
A size so large the runtime will not attempt it
A length does not have to be negative to be out of range. It can be positive, well-formed as an int, and still impossible:
// main.go
package main
import "fmt"
func main() {
n := 1 << 62
fmt.Println("before")
s := make([]int, n)
fmt.Println(len(s))
}
$ go run -trimpath main.go
before
panic: runtime error: makeslice: len out of range
goroutine 1 [running]:
main.main()
./main.go:8 +0x65
exit status 2
The message is the negative-length message again: makeslice: len out of range. A length of 1 << 62 elements of 8 bytes each asks for more memory than the runtime will allocate, and make reports it the same way it reports -1 — as a length out of range — rather than attempting the allocation and dying inside it. That is worth knowing operationally: this shape is a clean, immediate panic at the make line, not a slow death by memory pressure. If a service dies this way, the trace points at the exact call that trusted the number.
Where does a number like 1 << 62 come from in a real program? Rarely from a literal. It comes from a length field decoded from a network message or a file header and used directly as an allocation size, or from a count multiplied by a record size with no ceiling. The defense is a ceiling, applied where the number enters: a protocol that never legitimately carries more than a million records should reject a claim of a billion before that claim becomes a make argument — not because the panic is unclear, but because a panic per bad request is a denial-of-service surface wearing a stack trace. Return an error at the boundary instead.
Overflow: the size that wraps to negative before make ever sees it
The subtlest shape computes its own bad value. Nothing in this program is a negative literal, and no input is read at all:
// main.go
package main
import "fmt"
func main() {
count := 1 << 62
total := count * 2
fmt.Println("total:", total)
s := make([]int, total)
fmt.Println(len(s))
}
$ go run -trimpath main.go
total: -9223372036854775808
panic: runtime error: makeslice: len out of range
goroutine 1 [running]:
main.main()
./main.go:9 +0x91
exit status 2
Walk the arithmetic. count is 1 << 62, a positive int. Doubling it needs one bit more than a signed 64-bit int holds, so total wraps to the most negative int there is: -9223372036854775808. That print is the whole lesson — the program itself shows you the wrapped value one line before make consumes it and panics with len out of range, exactly as if someone had passed -1.
Go integer arithmetic does not panic on overflow. Signed integers wrap, silently, by two's-complement rules, and the wrapped value flows onward as an ordinary int until something with a range check — like make — finally rejects it. So the panic line and the bug line are different lines, and in a real program they are usually in different functions: a size is computed in one place (records * recordSize, pages << pageShift, count + count), overflows there, and is rejected several calls later at an allocation. If a len out of range panic shows a length that no input could explain, suspect the arithmetic, not the input. Recompute the size in a wider type or with an explicit check — divide before you multiply, or compare against a maximum before the multiplication happens — and reject the size as an error while it is still a size, instead of letting it become a panic when it becomes an allocation.
One neighboring outcome is worth ruling out. An overflowing computation can also wrap to a small positive number or to zero, and then make succeeds — with a slice far smaller than the program intended. No panic, no trace, just wrong capacity downstream and data quietly truncated or overwritten by later logic. The panic shapes in this guide are the lucky versions of an overflow. The check belongs on the arithmetic regardless of which way the wrap lands.
Constants versus variables: when the compiler catches it instead
Two of the shapes above failed to build. Here is the second one on its own, because the distinction decides where you look for this bug:
// main.go
package main
import "fmt"
func main() {
s := make([]int, -1)
fmt.Println(len(s))
}
$ go run -trimpath main.go
# command-line-arguments
./main.go:6:19: invalid argument: index -1 (constant of type int) must not be negative
invalid argument: index -1 (constant of type int) must not be negative — again a compile error, not a panic. The specification states the rule behind both build failures: a constant size argument to make must be non-negative and representable by a value of type int, and when both size arguments are constant, the length must be no larger than the capacity. Constants are known at compile time, so constant violations are compile errors, full stop. The program does not exist, and there is nothing to recover at run time.
Put the same values in variables and every one of those checks moves to run time, where failure is a panic. That is the whole distinction, and it explains the panic's natural habitat: test programs use constants and small literals, which the compiler vets, while production sizes come from variables — input, configuration, computed counts — which it cannot. A make call that "cannot panic, it worked in the test" usually means the test never fed it a variable with a production value in it. When you test size-handling code, the variable is the test: feed the function the negative, the swapped pair, and the overflowing count as inputs, and check that it returns errors for them — the fixed program below is written so that it can be tested exactly that way.
The fixed program
Here is a program that takes its count from outside — the parameter stands in for input — and never lets a bad count reach make at all:
// main.go
package main
import (
"fmt"
"math"
)
func build(count int) ([]int, error) {
if count < 0 {
return nil, fmt.Errorf("count %d is negative", count)
}
if count > math.MaxInt32 {
return nil, fmt.Errorf("count %d is too large", count)
}
hint := min(count, 1024)
s := make([]int, 0, hint)
for i := 0; i < count; i++ {
s = append(s, i*10)
}
return s, nil
}
func main() {
s, err := build(5)
fmt.Println(s, err)
fmt.Println(len(s), cap(s))
_, err = build(-1)
fmt.Println(err)
_, err = build(1 << 40)
fmt.Println(err)
}
$ go run -trimpath main.go
[0 10 20 30 40] <nil>
5 5
count -1 is negative
count 1099511627776 is too large
Check the shape against the failures above. The count is validated first, while it is still just a number: negative counts and counts past an explicit ceiling come back as errors, printed here and returnable to a caller in real code, instead of detonating at an allocation. The preallocation is a hint and is treated as one: min(count, 1024) caps the capacity argument at a sane bound, so even a legal-but-large count cannot turn the hint into a giant up-front allocation. And the slice itself is built by append, growing from that capped hint, so the final length is produced by the loop that fills it — the length and the data can never disagree, because the same operation produces both. build(5) returns [0 10 20 30 40] with a nil error, and the two bad counts return their errors with the program still alive to print them.
Nothing here calls recover. The program is safe because its checks sit where the bad values can still be handled — at the boundary, before make — which is the only place a check can turn a panic into an error. A recover wrapped around make would catch the same failure later, with less information and a half-built state to reason about. Validate the number, then allocate.
The fixes, ranked
Validate every length and capacity that came from outside the program, before make. Input, headers, configuration, counts from other systems: check the sign and check the ceiling at the boundary, and return an error for a bad value. This comes first because it converts the panic into a handled error at the one place where handling is still possible.
Check size arithmetic for overflow before it reaches make. Multiplications and shifts that produce a size get a guard: compare the inputs against a maximum first, divide before multiplying, or compute in a wider type and range-check the result. Go will not flag the wrap for you; the wrapped value looks like an ordinary int until make rejects it — or, worse, accepts its wrapped-to-small twin.
Grow with append instead of pre-sizing from an untrusted number. Start from an empty or small slice and let append grow it as real elements arrive. The length is then always a count of things that actually happened, and an untrusted count can at most make the loop run — where it can be bounded — not make an allocation explode.
Cap any preallocation hint at a sane bound. A capacity passed to make as a performance hint should be min(hint, bound) with a bound your program chooses, never the raw external number. A hint that can allocate gigabytes is not a hint; it is the untrusted input with a second name.
Decide which of length and capacity is authoritative when both are computed. The length-past-capacity panic is two computations disagreeing. Derive the capacity from the length, or drop the explicit capacity, but do not let two independent computations meet for the first time inside a make call.
Do not answer the panic with recover around make, or with clamping you cannot explain. Recovering hides which boundary let the value through, and silently clamping a length to fit a capacity truncates data without a signal. Reject bad sizes as errors, at the boundary, where the rejection can be logged and returned.
Which fix for which cause
| What the message and code show | Cause | Fix |
|---|---|---|
panic: runtime error: makeslice: len out of range, length is negative |
A count or size went below zero — subtraction, error path, or unvalidated input | Validate the sign at the boundary; return an error before make |
panic: runtime error: makeslice: len out of range, length is enormous |
An untrusted size was used directly as an allocation, or a size field was never given a ceiling | Enforce a maximum size where the number enters; reject larger claims as errors |
panic: runtime error: makeslice: len out of range, length is a huge negative no input explains |
Size arithmetic overflowed and wrapped before the make call |
Guard the arithmetic: pre-check against a maximum, divide before multiplying, or compute wider and range-check |
panic: runtime error: makeslice: cap out of range, length is larger than capacity |
Length and capacity were computed separately and disagree | Derive capacity from length, or drop the explicit capacity and let append grow the slice |
panic: runtime error: makeslice: cap out of range, capacity is negative or enormous |
A stale or unvalidated hint was passed as a real capacity | Cap the hint with min(hint, bound); validate a capacity from outside like any other input |
Build fails with must not be negative or length and capacity swapped |
The bad sizes are constants | Fix the literals — the compiler has already found the bug; there is no run-time issue to chase |
Checklist
- Find every
makewhose length or capacity is a variable. Trace each variable back: input, arithmetic, or a carried-forward hint? Each origin has its own check above. - Check the sign and the ceiling where external numbers enter, not at the
makecall. A check at the boundary returns an error; the same value unchecked becomes a panic at the allocation. - Audit size arithmetic — multiplications, shifts, additions of counts — for overflow, especially where the result feeds an allocation. Go wraps silently.
- Look for lengths and capacities computed in different places. If they meet for the first time inside
make, derive one from the other or drop the capacity. - Treat every capacity as a hint until proven otherwise, and cap hints with
min. A raw external number as a capacity argument is unvalidated input. - Prefer
appendgrowth when the count is not fully trusted. Let the length be a count of what actually arrived. - Test the size-handling function with variables, not literals: a negative, a swapped pair, and an overflowing count should each return an error. Constants would only test the compiler.
Related guides on this site
- Fix Go "panic: runtime error: index out of range" — Index Past the End, Negative Index, and the Off-by-One That Reaches Production — the neighboring panic, one step later in a slice's life.
makebuilt the slice legally, and then an index stepped outside the length thatmakeestablished; that guide works through the index shapes the way this one works through the allocation shapes. - Fix Go "panic: runtime error: slice bounds out of range" — Slicing Past Capacity, Backwards Bounds, and High Bound Past Capacity — where the length-versus-capacity rule from this guide does its daily work. A slice expression is checked against capacity, not just length, and that guide covers the bound combinations that panic once a slice already exists.
Sources
- The Go Programming Language, The Go Programming Language Specification — for
makeand slice creation (the built-in functionmaketakes a type, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions;make(T, n)is a slice of typeTwith lengthnand capacityn, andmake(T, n, m)is a slice of typeTwith lengthnand capacitym; a constant size argument must be non-negative and representable by a value of typeint; if bothnandmare provided and are constant, thennmust be no larger thanm; for slices and channels, ifnis negative or larger thanmat run time, a run-time panic occurs), for length and capacity (the capacity of a slice is the number of elements for which there is space allocated in the underlying array; at any time0 <= len(s) <= cap(s)holds; the length and capacity of anilslice are 0), and for theminbuilt-in used to cap the hint (the built-in functionsminandmaxcompute the smallest — or largest, respectively — value of a fixed number of arguments of ordered types).
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.