How to Detect and Fix Memory Leaks in Go

Detect Go memory leaks by enabling the Address Sanitizer with -asan or analyzing heap profiles using go tool pprof.

Go does not have a built-in command to detect memory leaks because its garbage collector automatically reclaims unused memory; leaks only occur when references to objects are unintentionally retained. To identify these retained references, run your program with the -asan flag to enable the Address Sanitizer, which reports leaks at runtime.

go build -asan -o myapp main.go
./myapp

If you suspect a leak in a running service, generate a heap profile to see which objects are consuming the most memory and inspect the stack traces to find the source of the retention.

go tool pprof http://localhost:6060/debug/pprof/heap

In the pprof interactive shell, type top to list the largest memory consumers and web to visualize the call graph.