Skip to content

runtime: go can allocate 30x the memory limit without panic'ing #68934

@ldemailly

Description

@ldemailly

Go version

1.22.6 up to gotip (and playground)

What did you do?

https://go.dev/play/p/Bid4PkG5o7e

package main
import (
	"fmt"
	"runtime/debug"
	"strings"
)
func main() {
	lim := 2_000_000 // less than 2MiB
	debug.SetMemoryLimit(int64(lim))
	v := strings.Repeat("ABC", 10*lim) // 30x the limit
	fmt.Println(len(v))
}

What did you see happen?

No panic, prints
60000000

What did you expect to see?

panic

ps: I am aware GOMEMLIMIT is a soft limit, yet letting it go 30x above in a single alloc isn't a useful feature

I recommend in "large alloc" runtime.(*mcache).allocLarge() to check and panic instead of going ahead.

Here is what I had to do:
https://github.com/grol-io/grol/pull/159/files#diff-f75830b8bf11850b6726e69a5d72e2ac711fca76f0cc5bd457f4ffed15e397de
meanwhile

ps1: it can also fatal error: runtime: out of memory https://gist.github.com/ldemailly/915e043323fa160562f121766990d9e3 if you push it above the OS limit but that's also not helpful as it terminates the program instead of failing the 1 bad alloc (and so the rest of the goroutines also end without a chance for cleanup)

ps2: numbers is the sample are tiny so it runs on the go playground but you can use GiB and get the same outcomes (either it allocates many times over the limit without breaking a sweat, or get OOM killed by the OS or gets the fatal error depending on the numbers) - of note that calling runtime.GC() before/after/inbetween doesn't help
https://github.com/ldemailly/go-scratch/blob/main/membug/membug.go has more stuff I tried to make it panic

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.compiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    Status

    Done

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions