9

A colleague of mine is convinced there is a memory leak in Oracle's odp.net ado.net implementation. He has written a test program to test this theory and is doing the following after calling dispose on each object in order to determine how much memory is being freed:

PerformanceCounter p = new PerformanceCounter("Memory", "Available Bytes");

GC.Collect();
GC.WaitForPendingFinalizers();

float mem = p.NextValue();

The resulting performance value is then compared with a value retrieved prior to disposing of the object. Will this produce accurate results?

zaq
  • 2,571
  • 3
  • 31
  • 39
  • 10
    No, that's not how the memory manager works. After it has gone through the trouble of allocating virtual memory space, it puts released blocks back on the free block list, ready to get re-used again later. – Hans Passant May 02 '12 at 00:31
  • Have you tried using ProcessExplorer to monitor .NET memory and system memory usage within your process? You have not stated what type of memory is leaking... – GregC May 02 '12 at 00:25
  • We don't know what type of memory is leaking, that is part of the reason for the test, to confirm that there is a problem. My question is to confirm if the test is a valid one. – zaq May 02 '12 at 16:13
  • why w using dispose() method? – Lijo Jun 26 '14 at 08:07

1 Answers1

2

I think the best way to do this is to use GC.GetTotalMemory(true). You can call it before allocating the object to record how much memory was allocated then. Then you create your object, maybe perform some operation on it, dispose it, make sure there are no references to it (probably just setting the local variable to null) and then call it again.

Keep in might that the returned value might not be completely exact, per the documentation, the method will return:

A number that is the best available approximation of the number of bytes currently allocated in managed memory.

After that, you can compare the two values. If you do this repeatedly, you can see whether the object is actually leaking managed memory.

Of course, this won't help you if the object leaks unmanaged memory.

Another option is to use a memory profiler, but that might be an overkill if you know where exactly the memory might leak.

svick
  • 236,525
  • 50
  • 385
  • 514
  • Thanks for the idea on how to better get the results. Does this mean there is something wrong with the approach I posted? Why is this a better approach? – zaq May 04 '12 at 21:34
  • 2
    Yeah, your approach is wrong, read the comment by Hans Passant. When the CLR collects garbage, it usually doesn't return the memory back to the system, so you might not see any change in Available Bytes, even though the memory was actually freed. – svick May 04 '12 at 22:19