A memory leak in Go occurs when your program allocates memory that is never freed, causing memory usage to grow indefinitely until the process crashes. For pure Go code, the garbage collector handles this automatically, so leaks usually stem from holding references to large objects in global variables or maps, or from C code (via cgo) that allocates memory without freeing it. Use the pprof tool to identify leaks by capturing a heap profile and analyzing which objects are retaining memory.
# 1. Run your program with the pprof HTTP server
export GODEBUG=gctrace=1
your-go-program
# 2. In a separate terminal, connect to the pprof server (default port 6060)
pprof http://localhost:6060/debug/pprof/heap
# 3. Inside the pprof interactive shell, type these commands:
top
list <function_name>
exit
If the leak is in C code (cgo), enable the Leak Sanitizer (LSAN) by setting CGO_LDFLAGS and CGO_CFLAGS to include -fsanitize=leak and -g, then rebuild and run your program to see the exact C stack trace of the leak.