How to Analyze Memory (Heap) Profiles in Go

Generate and analyze Go heap profiles using go tool pprof to identify memory allocation hotspots and leaks.

Generate a heap profile with go tool pprof to identify memory allocations and leaks in your Go application. Run your program with the -memprofilerate flag to control sampling density, then analyze the output using the pprof tool.

# Enable heap profiling and run your program
export GODEBUG=gctrace=1
GOMEMLIMIT=100MiB go run -memprofilerate=1 main.go

# Analyze the generated heap profile
# (Replace 'heap.prof' with your actual profile file path)
go tool pprof -http=:8080 heap.prof

The browser will open an interactive graph showing allocation hotspots. Click nodes to see specific functions and line numbers responsible for memory usage.