How to Detect Memory Leaks in Go

Detect Go memory leaks using the runtime memory profiler with pprof or by compiling with AddressSanitizer (asan) to identify unreleased memory allocations.

Use the Go runtime's built-in memory profiler to detect leaks by enabling it, triggering a garbage collection, and comparing heap snapshots before and after your workload.

export GODEBUG=gctrace=1
go test -memprofile=mem.out -run=YourLeakyTest
pprof -top ./your_binary mem.out

Alternatively, compile with the AddressSanitizer to catch leaks at runtime:

go build -asan -o your_binary your_package
./your_binary

If using CGO, ensure GODEBUG=asan=1 is set or use go build -asan to enable the LeakSanitizer (LSAN) which reports leaks like detected memory leaks.