Question: Detecting memory leak by monitoring ReadMemStats

Hello fellow gophers!

I have a question regarding detecting memory leaks. There is an idea of detecting potential memory leak by monitoring memory. I have implemented a demo that runs a program and in a separate goroutine records runtime.MemStats. Currently, I just look at HeapAlloc every record and then try to seek out the pattern when there is a simulated memory leak. The simulated memory leak that I chose is to open 100000 times one file in a loop but leave it open. It accumulates 1MB approximately from storing file handlers.

I thought that HeapAlloc or HeapInuse or StackInuse would increase as the simulated memory leak accumulates more memory. But it is not the case, unfortunately.

Thanks for you attention!

Hi, @Highzest, and welcome to the forum!

I’m unclear on what you’re question actually is; are you asking why HeapAlloc or HeapInuse or StackInuse didn’t show what you want? Or what you should use instead? Both?

Yes, both. I do not know the reason those memory stats do not hint a potential existence of the memory leak. And how can use MemStats to show a potential memory leak?

this is only scratching the surface. Think about it, your sample programs detects memory usage is now 1Mb more than 1 hour ago. How do you decide if this is a leak, or normal memory usage ? I find that to be the hard part.

Also, the runtime.MemStats appraoch cuases your program to perform more work. It could be better if you simply query the operating system in a terminal, or have a separate program altogether, to do this monitoring.

You need to post your code. Perhaps the compiler realizes this stuff is no longer used and does not actually store it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.